Archive
[flask] generate a secret key
Problem
To implement CSRF protection, Flask-WTF needs the application to configure an encryption key. This key is used to generate encrypted tokens that are used to verify the authenticity of requests with form data.
It looks like this:
app = Flask(__name__) app.config['SECRET_KEY'] = '<the super secret key comes here>'
What secret key to use? How to generate this secret key?
Solution #1
In the official Quickstart the following method is suggested:
>>> import os
>>> os.urandom(24)
'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'
Just take that thing and copy/paste it into your code and you’re done.
Solution #2
In Django, when you create a new project, you get a settings file that contains a freshly generated 50 characters long secret key. Why not reuse this part from Django? The relevant section was easy to locate in the source code of Django:
import random
random = random.SystemRandom()
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits.
Taken from the django.utils.crypto module.
"""
return ''.join(random.choice(allowed_chars) for i in range(length))
def get_secret_key():
"""
Create a random secret key.
Taken from the Django project.
"""
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
return get_random_string(50, chars)
Its usage is very simple: just call the “get_secret_key()” function and copy/paste the output into your code.
[django] virtualenvwrapper with Python 3
Problem
Django 1.7 came out ten days ago. If you look at the updated poll tutorial, you will notice that it’s written for Python 3! So far I’ve used Python 2 only, so I thought I would redo this tutorial for two reasons: (1) learn about migrations, and (2) start using Python 3.
For my Django projects I use virtualenvwrapper to manage my virtual environments, so the first question was: how to create a Python 3 virt. env. with virtualenvwrapper?
Well, maybe my installation got corrupted somehow, but I ran into this problem:
$ mkvirtualenv -p `which python3` tmpenv
Running virtualenv with interpreter /usr/bin/python3
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 8, in <module>
import base64
File "/usr/lib/python3.4/base64.py", line 9, in <module>
import re
File "/usr/lib/python3.4/re.py", line 324, in <module>
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in <module>
from copy_reg import *
ImportError: No module named 'copy_reg'
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 53, in apport_excepthook
if not enabled():
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 24, in enabled
import re
File "/usr/lib/python3.4/re.py", line 324, in <module>
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in <module>
from copy_reg import *
ImportError: No module named 'copy_reg'
Original exception was:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 8, in <module>
import base64
File "/usr/lib/python3.4/base64.py", line 9, in <module>
import re
File "/usr/lib/python3.4/re.py", line 324, in <module>
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in <module>
from copy_reg import *
ImportError: No module named 'copy_reg'
Solution
I posted this question to reddit (see here) and I found the following solution:
First, install pip3:
sudo apt-get install python3-pip sudo pip3 install virtualenvwrapper
Then, add the following lines to your .bashrc:
export WORKON_HOME=$HOME/.virtualenvs export PROJECT_HOME=$HOME/workspace # customize if needed export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv source /usr/local/bin/virtualenvwrapper.sh
Try if it works for you. In my case, I had to edit the file “/usr/local/bin/virtualenv“. I changed its first line to
#!/usr/bin/env python3
The consequence of changing the first line was that creating Python 3 environments became the default, but at least it works now.
Create a Python 3 virt. env.:
mktmpenv
Create a Python 2 virt. env.:
mktmpenv -p `which python2`
If you use the command “virtualenv“, it will also create Python 3 environments by default. Thus, “virtualenv myproject3” will be a Python 3 env., while “virtualenv -p python2 myproject2” will be a Python 2 env.
[django] awesome Django apps, projects and resources
A curated list of awesome Django apps, projects and resources: https://github.com/rosarior/awesome-django.
[django] must-watch videos
Must-watch videos about Django (or about Python as applied to Django): https://github.com/rosarior/django-must-watch.
[django] Heroku with GoDaddy
Problem
You put your Django project on Heroku and you register a custom domain name for it at GoDaddy. How to assign this domain name to your project on Heroku?
Solution
- Heroku with GoDaddy @lifesforlearning.com (excellent)
- Setup Heroku and GoDaddy? @SO
[django] force HTTPS on Heroku
django-sslify forces SSL on your Django site. It has an excellent documentation, can be set up in a few minutes.
I tried it on Heroku and it works well.
[django] deploy Django on Heroku
Follow the guide above to deploy your Django project on Heroku.
[django] create a formatted string with the Django template system
Problem
In an application I wanted to send formatted HTML emails. For producing the body of the email, I wanted to use the Django template system. The task is very similar to creating a view. The difference is that I don’t want to send back the HTML to the client in the browser but I want to store it in a string.
Solution
The solution is very simple:
from django.template.loader import render_to_string
def email():
context = {'some_key': 'some_value'}
html = render_to_string('APP_NAME/email.html', context)
send_email(html)
This tip is from here.
[django] using PostgreSQL for local development
PostgreSQL is highly recommended for Django. In the book “Two Scoops of Django” it is written that you should use the same DBMS that you will use in production. Many people use SQLite3 for local development and PostgreSQL in production but that will lead to surprises. So, if you plan to use PostgreSQL in production, then use PostgreSQL on your localhost too.
Question
How to set up and configure PostgreSQL on localhost? How to make it work with Django?
Answer
I found the answers to these questions here: How To Install and Configure Django with Postgres, Nginx, and Gunicorn.
PostgreSQL for local development
Long version:
# switch to user "postgres" $ sudo su - postgres [sudo] password for jabba: # notice "postgres" in the prompt postgres@jabba-uplink:~$ createdb mydb # create a database user if you don't have one yet postgres@jabba-uplink:~$ createuser myuser -P Enter password for new role: Enter it again: # grant access postgres@jabba-uplink:~$ psql psql (9.3.5) Type "help" for help. postgres=# GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser; GRANT postgres=#
Short version (if you already have a database user):
$ sudo su - postgres postgres$ createdb mydb postgres$ psql psql (9.3.5) Type "help" for help. postgres=# GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser; GRANT postgres=#
[django] init_app.py: complete the initialization of an app.
I wrote a simple script called init_app.py that completes the initialization of a Django application.
You create a new app. like this:
./manage.py startapp APP_NAME
However, the generated app. is far from complete. Put init_app.py next to manage.py (in the same folder) and execute the following command:
./init_app.py APP_NAME
Currently, it performs the following actions:
- inside the app., create the folder
static/APP_NAME - inside the app., create the folder
templates/APP_NAME - inside the app., create a sample
urls.pyfile
Links

You must be logged in to post a comment.