Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest with JWT authentiction
I would like to know how to perform a full login with django rest framework using JWT tokens for authentication. Here is part of the login code: @api_view(['POST']) def login_user(request): data=request.data serialized=UserSerializer(data=data) if serialized.is_valid(): email=serialized.data['email'] password=serialized.data['password'] user=authenticate(request, username=email, password=password) if user is not None: try: payload = JWT_PAYLOAD_HANDLER(user) jwt_token = JWT_ENCODE_HANDLER(payload) login(request,user) message="Logged in successfully" except User.DoesNotExist: message="User does not exist" else: message="User does not exist " data={ "message": message, "token": jwt_token } return JsonResponse(data) I am a bit lost. Could anybody guide me please -
How to auto refresh the page without left the last place of user
I am building a BlogApp and I am stuck on a Problem. I am making a Blog Page in which Users can upload Blogs. What i am trying to do I want Blog page to auto refresh the Page. without auto going at the Top of the Page. I want user to stay still on that place where user was before refresh. What have i tried <script> window.setTimeout(function () { location.href = 'http://127.0.0.1:8000/blog_posts'; }, 5000); //refresh/redirect after 5 seconds. </script> What's the problem in this JavaScript Code ^ In the JavaScript code below. It is working fine, It refresh the page very well in every 5 seconds. BUT when it refresh the page then if i am scrolling down while seeing blogposts then Page Refresh, then after refresh i find myself on top of the page. ( If a user is scrolling down and JavaScript refresh the page then the user find himself/herself on top the page ). That's Why its a Big Problem. I don't know what to do. Any help would be Appreciated. Thank You in Advance. -
Is it possible to create snake case `related_name` from class interpolation in Django related fields?
Django allows us to use '%(class)s' to automatically create related name from mixins. But when I have a ClassName I'd rather access it using class_name, not classname. I know it's only semantics but I was wondering if it's possible to adjust model field to make it snake case instead. I was browsing through django.db.models.fields but I can't find where the class interpolation is happening. Example code from django.db import models class User(models.Model): pass class UserRelatedMixin(models.Model): user = models.OneToOneField( to=User, parent_link=True, on_delete=models.CASCADE, related_name='%(class)s', related_query_name="%(class)s", ) class Meta: abstract = True class HomeAddress(UserRelatedMixin): pass user = User.objects.first() What I have user.homeaddress What I want instead user.home_address Right now I'm using a @property but it won't allow ORM queries so it's a partial solution. -
Django rest framework update ManyToManyField
models.py class Game(models.Model): name = models.CharField(max_length=255) gamemodes = models.ManyToManyField(GameMode, related_name='gamemodes', blank=True) class GameMode(models.Model): name = models.CharField(max_length=255) serializers.py class GameModeSerializer(serializers.HyperlinkedModelSerializer): class Meta: fields = ['pk', 'name'] model = GameMode class GameSerializer(serializers.HyperlinkedModelSerializer): gamemodes = GameModeSerializer(many=True, required=False) class Meta: model = Game fields = ['pk', 'name', 'gamemodes'] Updating name works perfectly with PATCH. But how can I add a "gamemode" to the Game object in the rest framework? Best -
Django + Postgres - slow postgres queries revert previous model changes
I'm facing a strange issue where a model instance in django is updated several times in succession, but the first update statement sometimes hangs/takes a while in postgres and when it does execute, it overrides previous updates. This all happens in a pipeline of different tasks that alter the model. A simplified example: A simple model (the actual one has more fields, but no too large ~20-25 fields) and the processing logic: class Foo(models.Model): status = models.CharField(...) number = models.CharField(...) foo = models.CharField(...) bar = models.CharField(...) # As it's part of a framework, this method is expected to save the whole models instance def set_status(self, status): with transaction.atomic() self.status = status self.save() self.process_status(status) # A pipeline of different tasks that will be executed based on Foo.status processing_pipeline = { 'a': 'set_status_to_b', 'b': 'set_number', 'c': 'set_foo', 'd': 'set_bar' } def process_status(self, new_status): # finds a task from the pipeline based on new status and executes it task = self.processing_pipeline.get(new_status, None) if task: getattr(self, task)() def set_status_to_b(self): self.set_status('b') def set_number(self): self.number = 1 logger.info('Setting number to 1') if self.foo: self.set_status('d') else: self.set_status('c') def set_foo(self): self.foo = 'foo' logger.info('Setting foo') self.set_status('d') def set_bar(self): # this creates some related models self.create_m2m_relationships_somewhere() self.bar = 'bar' … -
The current path, chat/room/1/, didn't match any of these
I am practicing with Django 3 and I have a chat project with the name of educa . I try to run the project by python manage.py runserver and access http://127.0.0.1:8000/chat/room/1/ . I always get the following error messages: “Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/chat/room/1/ Using the URLconf defined in educa.urls, Django tried these URL patterns, in this order: 1.accounts/login/ [name='login'] 2.accounts/logout/ [name='logout'] 3.admin/ 4. course/ … ** The current path, chat/room/1/, didn't match any of these.” ** I really don’t know what’s wrong. Please someone help me .Thank you. The following are the files : educa/ruls.py : urlpatterns = [ … path('chat/', include('chat.urls', namespace='chat')), ] chat/urls.py: app_name = 'chat' urlpatterns = [ path('room/int:course_id/', views.course_chat_room, name='course_chat_room'), ] chat/views.py: @login_required def course_chat_room(request, course_id): ... return render(request,'chat/room.html', {'course': course}) chat/templates/chat/room.html: {% extends "base.html" %} {% block title %}Chat room for "{{ course.title }}"{% endblock %} {% block content %} …. {% endblock %} {% block domready %} ... {% endblock %} educa/settings.py: INSTALLED_APPS = [ ... 'chat', 'channels', ] -
how to add the multiple row data into postgresql db using django
I want to create a table inside the Django forms and the table consists of number of rows with different data. Whenever I run the code in database it shows only the 1st row data and not the next row data pls solve me this... -
Django ModelViewSet increase foreign key list limit
I'm using the django-rest-framework to make entries into the database, and can make POST requests from there, and select foreign keys from a drop down list for each attribute. However, the limit of entries to select is set to 1000, so when it surpasses this then I cannot select what I want. In my example below I have more than 1000 Owner entries in the database. How can I increase this limit? class CatViewSet(viewsets.ModelViewSet): queryset = Cats.objects.all() serializer_class = CatSerializer filter_fields = '__all__' class CatSerializer(serializers.ModelSerializer): class Meta: model = Cats fields = '__all__' class Cat(models.Model): pwner = models.ForeignKey(Owner, on_delete=models.CASCADE) name = models.CharField() router = routers.DefaultRouter() router.register(r'cats', CatViewSet) urlspatterns = [ path(r'', include(router.urls)) ] -
django admin : string index out of range error
Following is the traceback for the django admin erorr I am getting. I am able to open all admin pages except this one. I am using django with mongodb. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/datarepo/production/ Django Version: 2.2.8 Python Version: 3.7.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'datarepo', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Abhi\Office\django\virtualenv1\lib\site-packages\django\contrib\admin\templates\admin\base.html, error at line 62 string index out of range 52 : {% endblock %} 53 : </div> 54 : {% endif %} 55 : {% endblock %} 56 : {% block nav-global %}{% endblock %} 57 : </div> 58 : <!-- END Header --> 59 : {% block breadcrumbs %} 60 : <div class="breadcrumbs"> 61 : <a href="{% url 'admin:index' %}">{% trans 'Home' %}</a> 62 : {% if t itle %} &rsaquo; {{ title }}{% endif %} 63 : </div> 64 : {% endblock %} 65 : {% endif %} 66 : 67 : {% block messages %} 68 : {% if messages %} 69 : <ul class="messagelist">{% for message in messages %} 70 : <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message|capfirst }}</li> 71 : {% endfor %}</ul> 72 : {% … -
Django - Tastypie inegrate url from third party-app
I'm writing a reusable app for a django application. The API endpoints of the application are written in tastypie I want to add a new endpoint (always with tastypie)from my app to the existing ones without touching the original app. This is my urls.py in my external app from myapp.views import MyResource from originalapp.urls import api from originalapp.urls import routers api.register(MyResource()) router = routers.DynamicRouter() The api imported is the origin Api() object needed for tastypie Even if i update the app via pip the new endpoint is not available in the urls list of the application. Any suggestion? -
background-size: 100% 100% doesn't work after uploading
I have a Django site, and when I run it on my local machine everything is fine, but when I make it to pythonanywhere.com one little problem appears: somewhy and somehow my background image doesn't want to fill the whole page even though it does on my local host (using the same browser, so the problem is not here).. body { background: url("images/classes.jpg") no-repeat center center fixed; background-size: 100% 100%; } It seems to me like {background-size: 100% 100%} just... doesn't work? I wonder what might be the problem. https://github.com/Seltsamermann/Specs-SL-PvP (in case that might help somehow) https://github.com/Seltsamermann/Specs-SL-PvP/blob/master/main/templates/main/classes.html https://github.com/Seltsamermann/Specs-SL-PvP/blob/master/main/static/main/style_classes.css -
Get instance by file name for a file in ImageField
Django 3.1.6 class ResponsiveImage(models.Model): responsive_image = models.ImageField(upload_to=_raster_img_upload_to) I want to find an instance by the image file_name: file_name = 'img/raster/0a8449e7-8e50-4c02-853e-59a25592770d/img_144_96_fallback_3x_4.fallback' ResponsiveImage.objects.get(responsive_image__name=file_name) But this gets an error: {FieldError}Unsupported lookup 'name' for ImageField or join on the field not permitted. Could you help me? -
How to send the value of XMLHttpRequest.save() to django view?
I have an AJAX/XMLHttpRequest and I want to send the result of window.confirm to view and use it. Currently this is my js: $(".release_hold").click(function () { var id = $(this).val(); $.ajax({ url: "/account/release_hold/" + id + "/", dataType: "json", success: function (data) { if (data.message != null) { // alert(data.message); result = window.confirm(data.message) == true; alert(result); if (result) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", "../release_hold/" + id + "/", true); # I think this should be POST. xmlhttp.send(result); } } }, }); }); Now on my views.py, I dont know if I need/how to add the result in my parameter. Once the result of windows.confirm is inserted, I can proceed. def release_hold(request, id, *args, **kwargs): ... if request.is_ajax() and request.POST : # Add result here. .... data = { 'message': "RELEASE DONE" } else: .... data = { 'message': "Are you sure you want to release record?" } return JsonResponse(data) -
DRF - How to queryset to only objects that the user is the owner of within an intermediate model?
I'm my DRF API, I have an intermediate model Ingredient that links two models, Product and Recipe. class Product(models.Model): name = models.CharField() class Recipe(models.Model): name = models.CharField() user = models.ForeignKey(User, on_delete=models.CASCADE) ingredients = models.ManyToManyField(Product, through='ingredient') class Ingredient(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) quantity = models.FloatField(default=0) In my current DRF generics.CreateAPIView for Ingredient, I want it to only display and allow a user to see and send a post request to create a new Ingredient entry for a Recipe that they own. But right now it keeps displaying Recipes for all users. I tried filtering the Recipe for the Ingredient model in my serializers.py with: serializers.py: class IngredientPostSerializer(serializers.ModelSerializer): recipes = serializers.SerializerMethodField() def get_recipes(self, obj): recipes = Recipe.objects.filter(user_id=self.request.user.id) return recipes class Meta: model = Ingredient fields = '__all__' -
Django email won`t send inside a view function
def contactform(request): if request.method == 'GET': form = contact_form() else: form = contact_form(request.POST) if form.is_valid(): contact_name = form.cleaned_data['aname'] contact_email = form.cleaned_data['aemail'] contact_subject = form.cleaned_data['asubject'] contact_message = form.cleaned_data['rmessage'] try: email_from = settings.EMAIL_HOST_USER recipient_list = ['xxx@gmail.com'] html_message = render_to_string('main/contact.html', {'contact_email': contact_email, 'contact_name': contact_name, 'contact_message': contact_message}) msg = EmailMessage(contact_subject, html_message, email_from, recipient_list) msg.content_subtype = "html" msg.send() except ValueError: return HttpResponse('Invalid header found.') return render(request, "main/home.html", {'successcform': 'Success! Thank you for your message. We will reply shortly.', 'contactform': form}) return render(request, "main/home.html", {'contactform': form}) This works well, the email is sended when someone fill the contact form, but if i use the send mail code with : def signupuser(request): if request.method == 'GET': return render(request, 'main/signupuser.html', {'form':UserCreationForm()}) else: if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) email_from = settings.EMAIL_HOST_USER recipient_list = [request.POST['username']] contact_subject = [' ,thank you for registering to our site.'] html_message = render_to_string('main/signupuser.html', {'username': request.POST['username']}) msg = EmailMessage(contact_subject, html_message, email_from, recipient_list) msg.content_subtype = "html" msg.send() return redirect('currenttodos') except IntegrityError: return render(request, 'todo/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: return render(request, 'todo/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'}) The email wont send, the user when registering dont receive any email. Simply doesn`t work … -
AttributeError at /add/...Getting 'str' object has no attribute 'get' in Django.Atrri
models.py I write this code for creating a form which has two fileds named Title and Desc from django.db import models.Here is models.py code. class Post(models.Model): title = models.CharField(max_length=200) desc = models.TextField() And Here is forms.py Code forms.py from django import forms from django.contrib.auth.forms import UserCreationForm,AuthenticationForm,UsernameField from django.contrib.auth.models import User from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','desc'] # label = {'title':'Title','desc':'Description'} widgets={'title':forms.TextInput(attrs={'class':'form-control'}), 'desc':forms.Textarea(attrs={'class':'form-control'})} Here is the views.py code views.py from django.shortcuts import render,HttpResponseRedirect from .forms import SignUpForm,LoginForm,PostForm from django.contrib import messages from django.contrib.auth import authenticate,login,logout from .models import Post def add_post(request): if request.user.is_authenticated: if request.method == "POST": form = PostForm(request.method) if form.is_valid(): title1 = form.cleaned_data['title'] description = form.cleaned_data['desc'] pst = Post(title=title1,desc=description) pst.save() form = PostForm() else: form = PostForm() return render(request,'blog_app/addpost.html',{'form':form}) else: return HttpResponseRedirect('/login/') Here is the addpost.html adpost.html {% extends 'blog_app/base.html' %} {% load static %} {% block content %} <div class="col-sm-10"> <h3 class="text-black my-5 alert alert-success">Add Post</h3> <form action="" method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Add" class="btn btn-primary"> <a href='{% url "dashboard"%}' class="btn btn-danger">Cancel</a> </form> </div> {% endblock content %} But When I click on Add Button I got this errorenter image description here What is the solution of it -
I don't know why job.module_set.all is empty in modal
I don't know why job.module_set.all is empty in modal class... This is my model. class Job(models.Model): build_start_time = models.DateTimeField('build start time', default=default_start_time, blank=True) branch = models.CharField(max_length=100) def __str__(self): return '{}_{}'.format(self.branch, self.build_start_time) class Module(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE) name = models.CharField(max_length=100) tag = models.CharField(max_length=100) hash_value = models.CharField(max_length=100) def __str__(self): return '{}_{}_{}'.format(self.name, self.tag, self.hash_value) This is part of my templates {% for job in latest_job_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ job.branch }}</td> <td>{{ job.build_start_time | date:'y-m-d H:i' }}</td> <td>{{ username }}</td> <td> {% for module in job.module_set.all|slice:":5" %} [{{ module.name }}] {% endfor %} </td> <td> <a href="#" class="btn btn-primary" data-toggle="modal" data-target="#detailModal"> DETAIL </a> <!-- Detail Modal --> <div class="modal fade" id="detailModal" tabindex="-1" role="dialog" aria-labelledby="detailModalLabel" data-backdrop="false"> <div class="modal-dialog modal-xl modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="detailModalLabel">{{ job.branch }} ({{ job.build_start_time }} {{ job.module_set.all }})</h4> Line 8. job.module_set.all is working propery(e.g. QuerySet([set1, ,set2]) but, Last Line is not working...(job.module_set.all is empty e.g. QuerySet([])) -
Unit/Functional Tests Vs Validators
I have recently started web development using Django. What confuses me the most that, why do we create tests for scenarios like "Check if password is provided", "Check if password is correct", "Check if a password is at least 8 characters long" etc. when we can do the same thing using validators in Django. Is there a specific advantage of using tests over validators? Thanks. -
define group from the current id in function based create view in django
i am trying to build chat website and in that only people in that group should see(thats not the problem). like we predefine user as request.user i want to definethe same group with id in address bar. till now created : homepage that has all group name , when click it gets current pk of group and render common template,in my views i need to define the group as id which i navigated. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', group.as_view(),name="group"), path('create/', views.create,name='create'), path('ajax/getusers',views.getusers,name='comments'), path('register/', views.register,name="register"), path('login/', views.login,name="login"), path('detail/<int:pk>', views.test,name="detail"), ] views def create(request,pk): if request.method == "POST": name = request.user author = request.user message = request.POST['message'] group = request['pk'] message = comments(user=author,message=message,name=name,group=group) message.save() return HttpResponse('') no render template because i am using ajax just using the function models class group(models.Model): group_name = models.CharField(max_length=100) group_user = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return f'{self.group_name} group' class comments(models.Model): userId = models.AutoField(primary_key=True) name = models.CharField(max_length=100) group = models.ForeignKey(group,on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE) message = models.TextField() date = models.TimeField(auto_now_add=True) def __str__(self): return f'{self.user} comments' -
remove username field django auth
Im new to Django, im open to hear any aproach and suggestions. I want to extend CustomAccountAdapter on AllAuth and populate username with email. I already did it on CustomSocialAccount. class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): def populate_user(self, request, sociallogin, data): user = super().populate_user(request, sociallogin, data) user.username = user.email return user Original class code def populate_user(self, request, sociallogin, data): """ Hook that can be used to further populate the user instance. For convenience, we populate several common fields. Note that the user instance being populated represents a suggested User instance that represents the social user that is in the process of being logged in. The User instance need not be completely valid and conflict free. For example, verifying whether or not the username already exists, is not a responsibility. """ username = data.get("username") first_name = data.get("first_name") last_name = data.get("last_name") email = data.get("email") name = data.get("name") user = sociallogin.user user_username(user, username or "") user_email(user, valid_email_or_none(email) or "") name_parts = (name or "").partition(" ") user_field(user, "first_name", first_name or name_parts[0]) user_field(user, "last_name", last_name or name_parts[2]) return user I cant do the same on CustomAccountAdapter because populate is a bit diferent. def populate_username(self, request, user): """ Fills in a valid username, if required and missing. If the username … -
Django Form does not save properly
I want to create a comment system. I can take username, doc_id, and comp_name, but I cannot get the comment_others. I think there is a problem saving the form. How can I fix it? views.py def ocr(request, id): pdf = get_object_or_404(Pdf, id=id) approval = ApprovalProcess(user_id=request.user, highest_rank=1) current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) if request.method == 'POST': form_2 = CommentForm(request.POST or None, instance=pdf) if form_2.is_valid(): comment_others = CommentFromOthers.objects.create( username=request.user, comp_name=userP[0].company, doc_id=pdf, ) comment_others.save() form_2.save() else: form_2 = CommentForm() comment_obj = CommentFromOthers.objects.filter(doc_id=pdf).order_by("-created_date") ..... models.py class CommentFromOthers(models.Model): comp_name = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True) doc_id = models.ForeignKey(Pdf, on_delete=models.DO_NOTHING, null=True) comment_others = RichTextField(blank=True) created_date = models.DateTimeField(default=datetime.now()) username = models.ForeignKey(UserProfile, on_delete=models.CASCADE) forms.py class CommentForm(forms.ModelForm): comments = RichTextField class Meta: model = CommentFromOthers fields = ('comment_others',) And there are two forms on the same page. When I save this form, the other form disappears. Why it could be happening? if request.method == 'POST': form = PdfRiskForm(request.POST, request.FILES, instance=pdf) if form.is_valid(): form.save() ... approval.save() else: form = PdfRiskForm() -
ModuleNotFoundError and ImportError even beeing right
Hello, thanks for your time. i'm trying to import models on seeders.py. Can someone please tell me what am i doing wrong, i've done this a hundred times and tried every single way: from winners.models import Player or from ..models import Player models.py: from django.db import models class Player (models.Model): name = models.CharField(max_length=100) sex = models.CharField(max_length=9, choices=sex_choices) age = models.PositiveIntegerField() height = models.DecimalField(max_digits=3, decimal_places=2) weight = models.PositiveIntegerField() team = models.CharField(max_length=120) by the way i've just started on linux may i havent set a envy variable right? -
Pagination links appearing null after applying Custom Pagination in django rest framework
I used custom pagination as mentioned in Django rest framework. In that, I had to use my project name to give the path to CustomPagination, but every time it says module not found. Then I manually import the pagination file in my views. It did work but my pagination links are appearing null. I have posted the picture here below. My views: from .pagination import CustomPagination class ProductAPIView(ListAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() serializer_class = ProductSerializer filterset_class = ProductFilter pagination_class = CustomPagination My pagination.py file class CustomPagination(PageNumberPagination): def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'results': data }) My settings file: # 'DEFAULT_PAGINATION_CLASS': 'RupseOnline.core.pagination.CustomPagination', 'PAGE_SIZE': 100, I have commented out the pagination class and imported it manually in views because it says module not found. -
Inherit Django application (a set of apps)
I have an architectural problem. My team have large Django DRF application (lets name it "portal-backend") combined of set of apps, not installed as a modules but created manually. The apps are: blogs, news, entries, adminapi, gallery, comments, events, ideas, microposts, reactions, moderation, profile, and so on (about 50 apps). Now I need to make some kind of "inheritance", use this product as a "base" in other team, and allow them to make changes in their nested classes. For example if they need to change class blogs.views.BlogViewSet, they can just inherit it by they own class. The "base" application must be installed with pip (if possible) or pulled from git (it's a single repo) So, the main portal-backend shouldnt be changed in other team, just used as a base and extended by inheritance Ideally my existing application should became some kind of high-level framework to create other portal-backends on the base of it with required modifications and additions on top of it. What variants I thought about: Split whole application into app-modules, put it into separate git repos, and install each app as a pip module. This method requires lots of work and has a problem that all apps are … -
how to share data between django server and python websocket server
I am writing a web app with Django in which I have to share some data with another python socket server running in parallel. I have tried using a common python file to store global variable. but since those server are two different processes it is not working. (I am not interested in using any database)