Django beginners issue issues - python

I am new to web development just pieced together my first django web app and integrated with apache using mod_wsgi.
the app has some 15 parameters on which you could query multiple SQL server databases and the result can be downloaded as .xls file; have deployed the same on the company network.
the problem is when i access the web app on one machine and set query parameters, the same parameters get set in the web app when i try opening it from a different machine (web client) .
Its like there is just one global object which is being served to all the web client.
Am using django template tags to set values in the app's html pages.
not using any models in the django project as am querying SQL server DB which are already built.
the query function from my views.py looks like
def query(self,request):
"""
"""
print "\n\n\t inside QUERY PAGE:",request.method,"\n\n"
self.SummaryOfResults_list = []
if self.vmd_cursor != -1:
self.vmd_cursor.close()
if request.method == 'POST':
QueryPage_post_dic = request.POST
print "\n\nQueryPage_post_dic :",QueryPage_post_dic
self.err_list = []
self.err_list = db_qry.validate_entry(QueryPage_post_dic)
if len(self.err_list):
return HttpResponseRedirect('/error/')
else:
channel_numbers,JPEG_Over_HTTP,Codec,format,rate_ctrl,transport,img_sz,BuildInfo_versions, self.numspinner_values_dic = db_qry.process_postdata(QueryPage_post_dic, self.numspinner_values_dic)
return self.get_result(request,channel_numbers,JPEG_Over_HTTP,Codec,format,rate_ctrl,transport,img_sz,BuildInfo_versions)
else:
print "\nself.Cam_Selected_list inside qry :",self.Cam_Selected_list
if (len(self.Cam_Selected_list) != 1):
return HttpResponseRedirect('/error/')
self.tc_dic,self.chnl_dic,self.enbl_dic,self.frmt_dic,self.cdectyp_dic,self.imgsz_dic,self.rtctrl_dic,self.jpg_ovr_http_dic,self.trnsprt_dic,self.cdec_dic,self.typ_dic,self.resolution_dic, self.vmd_cursor = populate_tbls.Read_RefTbls(self.Cam_Selected_list[0])
c = self.get_the_choices(self.Cam_Selected_list[0])
c['camera_type']= self.Cam_Selected_list[0]
for k,v in self.numspinner_values_dic.items():
c[k] = v
self.vmd_cursor.execute("SELECT DISTINCT [GD Build Info] FROM MAIN")
res_versions = self.vmd_cursor.fetchall()
version_list = []
ver_list = ['',' ']
for version in res_versions:
tmp_ver = version[0].encode()
if (tmp_ver not in ver_list):
version_list.append(tmp_ver)
c['build_info'] = version_list
print "\n\n c dic :",c
c.update(csrf(request))
return render_to_response('DBQuery.html',c)
and the dictionary being passed to render_to_response holds the values that setting checkboxes and multiselect boxes (dojo)
thanks

Its like there is just one global object which is being served to all the web client.
What you're saying is probably exactly what's happening. Unless you're building whatever object that self in that example code is anew for each request, it will be practically randomly shared between clients.

You can store your global variable in SQL DB that you are using. This way you can retain the value/state of the variable across request -> response cycle.
If you need faster response time explore Key->Value Pair in memory datastore like redis.
To add to what's mentioned by AKX I suggest that you read up on HTTP Request -> HTTP Response cycle and How web applications work.

Related

List databases return no results

I have a workspace with 2 databases shared with my integration, basically it works and I get 200 OK code.
That's the function I have, the headers contain the authentication token:
def listDatabases(self):
r = requests.get('https://api.notion.com/v1/databases', headers=self.headers)
if r.status_code == 200:
return r.json()
else:
return r.reason
And this is the result:
I think maybe those database permissions held by integration are inherited from the parent page.
From Notion API Reference (List databases):
Search pages for more details
This endpoint is no longer recommended, use search instead. This endpoint will only return explicitly shared pages, while search will also return child pages within explicitly shared pages.
An easy way to verify is to confirm if "based on xxx" is included under integration in the share option on the database page (not its parent page or inline database). if was, then that database will not return in "list databases" endpoint.
I believe it's because you are not sending the database id in the url
https://api.notion.com/v1/databases/**database_id**
if you don't specify the database_id it will take the first database which I assume is without any records.

Running my work webapp locally but cant access the correct site

I have been trying to get a Django webapp run in local. What I have done was set my debug = True and basically carried my settings.py file over from my test server. I finally got my python manage.py runserver [::]:8000 to run smoothly without errors. The problem that I am now having is that I cant access the correct idea.
Sorry for any incorrect terms but lets say my application is at three links www.webapp.com, www.buying.webapp.com and www.selling.webapp.com where the SITE_IDs are 1,2,3. I have learned to use localhost:8000 to access webapps before but that was with my simpler webapps.
Any help would be appreciated! Thank you.
EDIT:
I followed DOMAINS_URLCONF and found this
class SubdomainMiddleware:
""" Make the subdomain publicly available to classes """
def process_request(self, request):
domain_parts = request.get_host().split('.')
if (len(domain_parts) > 2):
subdomain = domain_parts[0]
if (subdomain.lower() == 'www'):
subdomain = None
domain = '.'.join(domain_parts[1:])
else:
subdomain = None
domain = request.get_host()
# if subdomain in settings.DOMAINS_URLCONF:
# request.__setattr__('urlconf',settings.DOMAINS_URLCONF[subdomain])
try:
current_site = Site.objects.get(domain=request.get_host())
except Site.DoesNotExist:
current_site = Site.objects.get(id=settings.SITE_ID)
request.current_site = current_site
#settings.SITE_ID = current_site.id
request.subdomain = subdomain
request.domain = domain
For that to work, you simply need different domains on your local machine. That can be simply achieved by editing your local /etc/hosts file (on windows it is C:\Windows\System32\drivers\etc\hosts). Simply add this line in it:
127.0.0.1 buying.x.localhost selling.x.localhost
Update:
After seeing your middleware code, there is one more caveat: local domains for buying and selling should have at least 3 parts. I've just added .x in the middle of domains above, so it should be parsed correctly by this middleware. You can structure those urls as you wish, but they have to have at least 3 parts and the first part has to match one of the subdomains of your project.
After doing this, if you type just localhost:8000 in the address bar of your browser, you should see the main page, by entering buying.x.localhost:8000 you will see the content of buying. subdomain and by entering selling.x.localhost:8000 you will see content of selling. subdomain.

mongoengine can not load data correctly in concurrency

in a web service (flask web server, deployed with gunicorn, gevent workers) , there is a request handler will query a set of objects and update the status like below:
def update_status(job_id,info_ids):
infos = Info.objects(job_id=job_id, info_id__in = info_ids)
if len(infos) == 0:
logger.error('infos are not found')
for i in infos:
pass
I'm sure the infos are in the database, other service will request to this in concurrency, but in some request , I logged the error in logs(infos are not found). I'm quite confused why the data can not be loaded sometimes.
I'm not sure about the other parts of your code, but I guess the Info class is your mongoengine document like this:
class Info(mongoengine.Document):
job_id = mongoengine.StringField(...)
info_id = mongoengine.StringField(...)
If it's true, you must use Info.objects instead of Info.object to access queryset of your collection (note the 's' at the end of objects). So, your code must be something like this:
infos = Info.objects(job_id=job_id, info_id__in = info_ids)

Flask session not persisting after refresh

I have this route in a flask app:
#APP.route('/comparisons', methods=['POST'])
def save_comparison():
if 'comparisons' not in session or not session['comparisons']:
session['comparisons'] = []
entity_id = request.form.get('entity_id')
session['comparisons'].append(entity_id)
session.modified = True
return entity_id
APP.secret_key = 'speakfriend'
This adds entity_ids to session['comparisons'] as expected. However, when I refresh the page, the session object does not have a 'comparisons' property anymore, so the list of comparisons is empty. What am I missing?
Update:
I left out what I didn't know was the important information. The vue app also makes calls to a flask api, which sets its own session. The SECRET_KEYs were different. So, when there was an api call between webserver calls (or visa versa) the session from one application would be replaced by the session from the other. Neither was mutually intelligible (different SECRET_KEYs). Since these are always deployed together using docker-compose the solution was to use a common an env variable to pass the same secret to both.

Using render_templete and static file, which one is faster in Flask

I'm developing an web app using Flask in Heroku. My web will have k news pages. Information for each page is stored in database. When user make a request in web browser, the returned page can be generated using render_templates() in Flask.
The problem is when all users request same page, render_templates() will be called multiple times for the same page => kind of wasting resources to do the same thing
I curious whether I should use render_templates() or I should generate k static pages and use there static file instead?
You can use Flask-Cache package.
Support built-in cache backends like dictionary, file system, memcached, redis, and also custom cache backends.
Example:
#cache.cached(timeout=50)
def index():
return render_template('index.html')
.
#cache.memoize(timeout=50)
def big_foo(a, b):
return a + b + random.randrange(0, 1000)
.
#cache.cached(timeout=50)
def big_foo():
return big_bar_calc()
Also another option [beside that] is using front page caching, like varnish.

Categories

Resources