Archive

Archive for the ‘django’ Category

[flask] generate a secret key

January 1, 2015 1 comment

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.

Advertisements
Categories: django, flask Tags: , ,

[django] virtualenvwrapper with Python 3

September 12, 2014 Leave a comment

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

August 12, 2014 Leave a comment

A curated list of awesome Django apps, projects and resources: https://github.com/rosarior/awesome-django.

Categories: django Tags:

[django] must-watch videos

August 12, 2014 Leave a comment

Must-watch videos about Django (or about Python as applied to Django): https://github.com/rosarior/django-must-watch.

Categories: django Tags: , , ,

[django] Heroku with GoDaddy

August 11, 2014 Leave a comment

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

Categories: django Tags: , , , ,

[django] force HTTPS on Heroku

August 7, 2014 Leave a comment

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.

Categories: django Tags: ,

[django] deploy Django on Heroku

August 7, 2014 Leave a comment

https://devcenter.heroku.com/articles/getting-started-with-django

Follow the guide above to deploy your Django project on Heroku.

Categories: django Tags: ,