When should I use the Flask.config vs. use flask.session? - python

Is there a rule for when to use Flask.config vs. flask.session to store variables?

Anything that is static, app-wide, doesn't change much, and has important information for all users, should use config. (e.g. secret keys, options to modify the app from project to project, emails, generic messages)
Session should only be used to store relevant user data as the data is modified through each page. (e.g. user login data, user preferences, user inputs from previous pages)
If you have to save something from Page 1 to Page 5 in your website for that particular user, then use session. Sessions should mainly be used based on the individual user.

Yes, most definitely.
The config is for global, project-level variables: the location of files, keys for any APIs you might be using, your database access settings, things like that.
The session is for variables related to the current user's session on the site: their previous choices on a multi-page form, preferences, login details, etc.
You definitely don't want to get these mixed up.

Related

Best approach for loading settings that can be modified in Flask

Hello all fellow StackOverFlow'ers,
I'm making an app in Flask that runs depending on settings that can be changed by administrator via a POST request in their admin-panel,
Actually, the only two things I came up with for doing this is using os.environ.get (Environment variables) [which i'm using now] or insert it to a PostreSQL Database config table and load it up
Anyway I will be storing settings such as a couple of API_URLs and their API_KEY, and some Conditions of checking like a success value where if condition in text .. else is applied to ... where admin can change them via the panel
I'm looking for the best performant approach for doing such thing.
Best regards.
If you're looking for the changes to only apply on a per-user basis (changes made by the admin only affect the admin), check out Flask's sessions. It works like a dictionary, but stores information in a cookie in the user's browser that can be programmatically accessed by Flask. Be warned that this data is stored in plain-text in the user's browser, so don't store anything sensitive here.
On the other hand, if you're looking for changes made by the admin to affect everybody visiting the website, you may just be able to store the settings in a variable, update them when the admin makes changes, and read them when responding to a request. If you want these settings to persist through a server restart, however, you'll need to write them to disk and then load them on server restart and save them to disk when they're changed. If this is a production-grade app and needs to be able to scale, I personally recommend using an SQLite file to store settings (or a SQL database if it really needs to scale), but this is a personal preference of mine. If this is just a personal app, storing settings in text files would be just fine.
Hope this helps!

Are there any ways other than authentication to tell the users apart?

In my app, the user can select a Youtube video that will be downloaded to MEDIA_ROOT folder and then also made available for the user to download.
Whenever the user chooses another video to download, the previous one is deleted from MEDIA_ROOT. So at any given moment there is only one video sitting in the MEDIA_ROOT folder for a particular user.
Is there any way - apart from implementing user authentication and associating the downloaded files with a user through foreign key, which I feel is an overkill for only this task - of telling the users apart whenever such download request is being made, so that one user's request does not cause the deletion of the file downloaded by some other user (as all the files sit in the same MEDIA_ROOT folder)?
Assuming you have some sort of web server, you can create custom links that redirect through your web server and pass IP information, etc, so you can distinguish a user before one downloads a video. That is certainly one way of doing it without authentication and since the app/platform that tracks user data is in-house you don't have to worry about foreign keys, etc.
You can use cookies to uniquely identify users. Web browsers will keep sending that cookie value to your web server for as long as the web browser's cookie store is not cleared. Make sure to generate an hard to guess value for the web browser to store and you to identify with so that one cannot bruteforce that value and get access to data meant for other users. The common way is to generate say a 32 characters string from a CSPRNG.
You can have a go at this question to find out how to set cookies in Python Django: Django Cookies, how can I set them?
I would personally use built in Django Cookie Sessions: https://docs.djangoproject.com/en/2.2/topics/http/sessions/#using-cookie-based-sessions

How do you find the login provider in Django-Allauth?

I saw the code in the accepted answer for this question:
How to access user names and profiles with django-allauth
But when I run a template with {{user.get_provider}}, nothing appears. I was expecting it to say either "LinkedIn Oauth2" or maybe "native". (Those are my two ways to log in.)
Are there special things you need to get the template calls working? Other template items are working fine, such as account.get_avatar_url.
To my knowledge the user profile doesn't record which credential was used to establish the current session, nor as far as I am aware does a list of a particular account's associated credential types automatically populate into the user context object (I'm not sure which you were trying to get from the question you asked).
You can access what credentials an account has available to it in python & export these to the context. See the socialaccount/connections.html template that comes with django-allauth as an example.

Django User Sessions, Cookies and Timeout

I'm working with a Django application and my current goal is to keep track of the user session with cookies. I have a feeling that, as always, my understanding is a bit off with regards to how I do this.
For starters, I would like to manage how long it has been since a user has logged in, that way I can successfully log them out if they haven't visited a new page in "x" hours. I am not sure what exactly is standard (for a social network).
Is this information I store on my server? Do cookies actually have any relevancy here? I've used cookies before to store things like a user's timezone, but I am struggling to deal with how I keep track of the user.
All I currently have in terms of user back end is from the django.contrib.auth package.
The only thing I really know how to do in terms of "grabbing" the user's info is done by using statements like if request.user.is_authenticated(): (etc.).
I realize this is somewhat of a complex question, so I will try and narrow it down:
How do I extend my existing information about the current user to capture "last activity" so I can log him/her out if they haven't been using the site in a certain period of time?
Do I need to define a custom user model?
My next step after is to create a different type of user, so I feel like I need to make custom user models - beyond just extending the normal user form to make a profile etc.
Thanks for your understanding,
I know I can be confusing when I don't understand things.
Thanks for your time,
James
You can configure the session middleware for logging out the user automatically,
configure the SESSION_COOKIE_AGE, to some low value, and provide the SESSION_SAVE_EVERY_REQUEST, as True.
This will automatically logout the user after certain inactivity, without any need of extending the profile.
SESSION_COOKIE_AGE
Default: 1209600 (2 weeks, in seconds)
>> The age of session cookies, in seconds.
SESSION_SAVE_EVERY_REQUEST
Default: False
>> Whether to save the session data on every request.
If this is False (default), then the session data will only be saved if it has been modified – that is, if any of its dictionary values have been assigned or deleted.
And for creating custom/extending User Profile, Django 1.5, comes with configurable User model, please check the docs for examples.

How can I create a single log-in and profile for a network of three sites using Django?

How can I create a single log-in and profile for a network of three sites using Django?
I have a network of three sites and instead of having the user create a profile at each of the three sites, I'd like the user to only need to register one time, and then be able to use all three.
Is there an elegant solution to this problem?
Let the sites share the databases. Hence they will have a common user table.
Take a look at the django sites framework: http://docs.djangoproject.com/en/dev/ref/contrib/sites/
Depends on your server(s).
Do all the sites have access to the same DB? Then use dcrodjer's answer.
If not, you can implement a OAuth style Single Signon Service, that the other sites authenticate against.
Ex:
site1.example.com
site2.example.com
site3.example.com
siteN.example.com
Would auth against oauth.example.com
If you can put those three sites into subdomains of a single domain, then I'm almost sure you can stick to what Django offers. What I'm writing about is something like this:
site1.mydomain.com
site2.mydomain.com
site3.mydomain.com
-- where login is implemented at mydomain.com.
Basically, mydomain.com should serve a small Django page that implements only the login form and maintains session for ".mydomain.com" domain (note the leading dot - it's required for the session to propagate to site1..3 subdomains). So if you log into mydomain.com, you're effectively logged into all three subsites.
And the easiest way to share server-side auth and session data is to make ubsites 1,2,3 use two databases, one small database shared with mydomain.com for auth and session data, and the other one specific to given site.

Categories