Django: two sessions in the same browser - python

I have a Django webapp that allows users to collaborate. Each user is given a link with a unique code they click to go to my site. On the first page visit, I store this unique code in request.session, and then on subsequent page visits I retrieve it to identify the user's record in the DB. I also store various other stuff about the user and their session in request.session.
I would like to allow two sessions to occur in different windows/tabs of the same browser. This is to make testing easier. My colleagues spend a lot of time testing multiple users using the site simultaneously. So far I have been instructing them to use different browsers or different browser profiles, so that the session cookie is not shared. But they always forget this instruction (or do it wrong) and end up confused when the app doesn't work as expected.
My idea is to put the user's unique code (called user_id) in each URL, and then subdivide request.session into multiple dictionaries, so my class-based view would have this:
def dispatch(...):
user_id = kwargs['user_id']
self.request_session = self.request.session[user_id]
Then use this variable self.request_session as I usually would:
self.request_session['time_started'] = now
...
And then before returning my response, assign it back:
self.request.session[user_id] = self.request_session
I think this should be fine, since own code would keep the two sessions isolated in 2 separate dictionaries, but maybe it would break down if Django (or even a 3rd party app) stores something in request.session. Wondering if anyone has a recommendation for another way to handle this.

Modern browsers (e.g. Firefox, Chromium, Brave, …) have the ability to open a page without reference to existing history, cookies, etc.
In Firefox this is termed “Private Browsing”; you open a “Private Window”.
In Brave this is termed a “Private Tab”.
In Chromium this is termed “Incognito Mode”.
By using any of these, you can make a new “session” that will not present as any other logged-in session. This should allow you to have an arbitrary number of sessions at once.

Related

Posting data to database through a "workflow" (Ex: on field changed to 20, create new record)

I'm looking to post new records on a user triggered basis (i.e. workflow). I've spent the last couple of days reasearching the best way to approach this and so far I've come up with the following ideas:
(1) Utilize Django signals to check for conditions on a field change, and then post data originating from my Django app.
(2) Utilize JS/AJAX on the front-end to post data to the app based upon a user changing certain fields.
(3) Utilize a prebuilt workflow app like http://viewflow.io/, again based upon changes triggers by users.
Of the three above options, is there a best practice? Are there any other options I'm not considering for how to take this workflow based approach to post new records?
The second approach of monitoring the changes in the front end and then calling a backend view to update go database would be a better approach because processing on the backend or any other site would put the processing on the server which would slow down the site whereas second approach is more of a client side solution thereby keeping server relieved.
I do not think there will be a data loss, you are just trying to monitor a change, as soon as it changes your view will update the database, you can also use cookies or sessions to keep appending values as a list and update the database when site closes. Also django gives https errors you could put proper try and except conditions in that case as well. Anyways cookies would be a good approach I think
For anyone that finds this post I ended up deciding to take the Signals route. Essentially I'm utilizing Signals to track when users change a fields, and based on the field that changes I'm performing certain actions on the database.
For testing purposes this has been working well. When I reach production with this project I'll try to update this post with any challenges I run into.
Example:
#receiver(pre_save, sender=subTaskChecklist)
def do_something_if_changed(sender, instance, **kwargs):
try:
obj = sender.objects.get(pk=instance.pk) #define obj as "old" before change values
except sender.DoesNotExist:
pass
else:
previous_Value = obj.FieldToTrack
new_Value = instance.FieldToTrack #instance represents the "new" after change object
DoSomethingWithChangedField(new_Value)

Is there a way to create read only dashboard in Apache Superset

So we have been using Apache Superset, It's a great tool.
The only frustration come from that there are a few dashboards we want to share with users outside the company.
I believe right now the way to do it is go from the Gamma user then create a read only role (Correct me if I'm wrong)
There are a few downside of this:
we need to create a view per user on each table to make sure that they do not see the records that they are not supposed to.
the access is given by datasource, so they will be able to see any dashboard that use the same datasource, which can be a problem sometimes.
all of these authentication is a lot of work to maintain.
I'm wondering if there is any way (or even hack) to simply share the graphs and tables as a dashboard, without any database access granted.
Like a frozen or snapshot of dashboard,
like the way Redash does it:
https://redash.io/help/user-guide/dashboards/sharing-dashboards
What you are looking for can be achieved through a combination of the public user and appending ?standalone=true to the dashboard url.
You also don't need the entire list of Gamma user permissions, the most important ones are can explore on superset, explore json on superset and datasource access and csrf token. This basically renders the dashboards without the superset menu and should make everything readonly.
We can achieve this by creating a custom role.
1. Can remove all the menu items
2. Can disable the dashboard edit button
3. Can give access to specific tables.
So a user cannot access any other dashboard or charts
Eg. Dashboard
Public dashboards
This is not meant for production. It’s for experiments or while doing a proof of concept.
#superset_config.py
PUBLIC_ROLE_LIKE_GAMMA = True
or
PUBLIC_ROLE_LIKE: Optional[str] = "Gamma"
After this, we need to re-run the init user (if already run)
docker-compose exec superset superset-init
Dashboards & charts can be embedded without superset header (Nav bar etc) by adding standalone=true parameter to the url, like this :
http://localhost:9000/superset/dashboard/world_health/?standalone=true
We need to grant database source permissions to public role for the data to be visible.
please see: https://sairamkrish.medium.com/apache-superset-custom-authentication-and-integrate-with-other-micro-services-8217956273c1
Superset is great, I'm glad people are talking about it since the days when it was AirBnB's Caravel. It has come a long way.
There is no 'official' solution for what you're looking for but there is a way to effectively get the same result. You said you wouldn't mind a 'hack' so...
Creating a table or a data source and exposing it to the 'public' group should do what you're looking to accomplish.

Django: Database caching to store web service result

I have a method to load all ideas from database. There are few comments on each idea.
I have store users id who commented on ideas, in respective table.
I have a web service which contains all the data related to user id
When i load a page, it took time to fetch information for all users using web service.
I want to use databse caching to store that web service response and use that later on.
How to achieve this, to reduce page load timing?
when should i store that web service response in cache table?
The Django documentation on the cache framework is pretty easy to follow and will show you exactly how to set up a database cache for pages and other things in your views, including for how long you'd like the cache to exist, TIMEOUT, as well as other arguments a cache can take.
Another way to speed up accessing your DB information is to take advantage of CONN_MAX_AGE for your database in your settings.py, who's time can be dependent on how often the database needs to be accessed or how much traffic the site gets (as an example). This is basically letting your DB connection know how long to stay open, and can be found in the settings documentation.
You can store information in a cache when something on the site occurs (such as a new comment) or when that particular request is made for a particular page. It can be entirely up to the needs of your project.

Persistent object with Django?

So I have a site that on a per-user basis, and it is expected to query a very large database, and flip through the results. Due to the size of the number of entries returned, I run the query once (which takes some time...), store the result in a global, and let folks iterate through the results (or download them) as they want.
Of course, this isn't scalable, as the globals are shared across sessions. What is the correct way to do this in Django? I looked at session management, but I always ran into the "xyz is not serializeable on json" issue. Do I look into how I do this correctly using sessions, or is there another preferred way to do this?
If the user is flipping through the results, you probably don't want to pull back and render any more than you have to. Most SQL dialects have TOP and LIMIT clauses that will let you pull back a limited range of results, as long as your data is ordered consistently. Django's Pagination classes are a nice abstraction of this on top of Django Model classes: https://docs.djangoproject.com/en/dev/topics/pagination/
I would be careful of storing large amounts of data in user sessions, as it won't scale as your number of users grows, and user sessions can stay around for a while after the user has left the site. If you're set on this option, make sure you read about clearing the expired sessions. Django doesn't do it for you:
https://docs.djangoproject.com/en/1.7/topics/http/sessions/#clearing-the-session-store

Django : How to count number of people viewed

I'm making a simple BBS application in Django and I want it so that whenever someone sees a post, the number of views on that post (post_view_no) is increased.
At the moment, I face two difficulties:
I need to limit the increase in post_view_no so that one user can only increase it once regardless of how many times the user refreshes/clicks on the post.
I also need to be able to track the users that are not logged in.
Regards to the first issue, it seems pretty easy as long as I create a model called 'View' and check the db but I have a feeling this may be an overkill.
In terms of second issue, all I can think of is using cookies / IP address to track the users but IP is hardly unique and I cannot figure out how to use cookies
I believe this is a common feature on forum/bbs solutions but google search only turned up with plugins or 'dumb' solutions that increase the view each time the post is viewed.
What would be the best way to go about this?
I think you can do both things via cookies. For example, when user visits a page, you can
Check if they have “viewed_post_%s” (where %s is post ID) key set in their session.
If they have, do nothing. If they don't, increase view_count numeric field of your corresponding Post object by one, and set the key (cookie) “viewed_post_%s” in their session (so that it won't count in future).
This would work with both anonymous and registered users, however by clearing cookies or setting up browser to reject them user can game the view count.
Now using cookies (sessions) with Django is quite easy: to set a value for current user, you just invoke something like
request.session['viewed_post_%s' % post.id] = True
in your view, and done. (Check the docs, and especially examples.)
Disclaimer: this is off the top of my head, I haven't done this personally, usually when there's a need to do some page view / activity tracking (so that you see what drives more traffic to your website, when users are more active, etc.) then there's a point in using a specialized system (e.g., Google Analytics, StatsD). But for some specific use case, or as an exercise, this should work.
Just to offer a secondary solution, which I think would work but is also prone to gaming (if coming by proxy or different devices). I haven't tried this either but I think it should work and wouldn't require to think about cookies, plus you aggregate some extra data which is noice.
I would make a model called TrackedPosts.
class TrackedPosts(models.Model):
post = models.ForeignKey(Post)
ip = models.CharField(max_length=16) #only accounting for ipv4
user = models.ForeignKey(User) #if you want to track logged in or anonymous
Then when you view a post, you would take the requests ip.
def my_post_view(request, post_id):
#you could check for logged in users as well.
tracked_post, created = TrackedPost.objects.get_or_create(post__pk=id, ip=request.ip, user=request.user) #note, not actual api
if created:
tracked_post.post.count += 1
tracked_post.post.save()
return render_to_response('')

Categories