Tips for in-depth customization of the Python Flask framework development environment

Source: Internet
Author: User
Tags virtualenv
More and more people are using the virtualenv virtual environment to deploy Python projects, including instance folders and version control settings for frameworks, here we will summarize some tips on deep customization of the Python Flask framework development environment. Flask environment configuration
Your application may require a large number of software packages to work properly. If you do not need the Flask package, you may have read the wrong tutorial. When an application is running, the environment of your application is basically the foundation of everything. We are lucky because there are many ways for us to easily manage our environment.
Use virtualenv to manage your environment
Virtualenv is a tool used to isolate your applications in a so-called virtual environment. A virtual environment is a directory containing the software your application depends on. A virtual environment can also change your environment variables to maintain the environment variables contained in your development environment. You do not need to download packages, such as Flask, to your system-level or user-level package directory. we can download them to an independent directory that is only used by our application. This allows you to easily specify the Python version used and the packages that each project depends on.
Virtualenv also allows you to use different versions of the same package in different projects. This flexibility may be very important if you are using an old system and there are several projects on it that require different versions.
When using virtualenv, you usually only need to install several Python packages on your system. One of them is virtualenv itself. You can use Pip to install the virtualenv package.
Once virtualenv is installed on your system, you can start to create a virtual environment. Go to the directory where your project is located and run the virtualenv command. It requires a parameter, which is the target Directory of the virtual environment. The following figure shows its approximate appearance.

$ virtualenv venvNew python executable in venv/bin/pythonInstalling Setuptools...........[...].....done.Installing Pip..................[...].....done.

Virtualenv creates a new directory. the dependency package is installed in this directory.
Once a new virtual environment has been created, you must activate it by launching the bin/activate script created in the virtual environment.

$ which python/usr/local/bin/python$ source venv/bin/activate(venv)$ which python/Users/robert/Code/myapp/venv/bin/python

The bin/activate script changes your shell environment variables so that everything points to the new virtual environment rather than the global system. You can see the effect in the code block above. After activation, the python command points to the Python bin directory in the virtual environment. After the virtual environment is activated, dependent packages installed with Pip will be downloaded to the virtual environment rather than the global system.
You may notice that the prompt in shell has changed. Virtualenv pre-specifies the name of the currently activated virtual environment, so you will know that you are not working on the global system.
You can run the deactivate command to disable your virtual environment.

(venv)$ deactivate

Virtualenvwrapper
Virtualenvwrapper is a software package used to manage the virtual environment created by virtualenv. I don't want to mention this tool until you see the basic knowledge of virtualenv so that you can understand what it has improved and why we should use it.
The virtual environment directory created in the previous section will bring some confusion to your project Library. You only need to activate the virtual environment to interact with it, but it should not appear in version control, so this virtual environment directory should not be here. The solution is to use virtualenvwrapper. This package puts all your virtual environments in one directory. the default value is ~ /. Virtualenvs /.
To install virtualenvwrapper, follow the instructions in the document that is located in the http://virtualenvwrapper.readthedocs.org/en/latest/install.html.
Make sure that you have disabled all virtual environments before installing virtualenvwrapper. You need to install it in a global system instead of a virtual environment.
Now, you do not need to run virtualenv to create an environment. you need to run mkvirtualenv:

$ mkvirtualenv rocketNew python executable in rocket/bin/pythonInstalling setuptools...........[...].....done.Installing pip..................[...].....done.(rocket)$

Mkvirtualenv creates a folder in your virtual environment directory and activates the virtual environment for you. Just like the virtualenv above, python and pip point to the binary files in the virtual environment rather than the global system. To activate a specific environment, run workon [environment name]. Deactivate still disables the virtual environment.
Install dependency packages
With the development of the project, you will find that the list of dependent packages will increase. Dozens of Python packages are required to run a Flask application. The simplest way to manage these problems is to use a simple text file. Pip can generate a text file listing all installed packages. You can also read the list of files and install each of them on a new system or in a new environment.

Pip freeze:

Requirements.txt is a text file used by many Flask applications to list all the packages required to run the application. This code block is used to demonstrate how to create this file and then the next code block to demonstrate how to install the dependency package using this file in a new environment.

(rocket)$ pip freeze > requirements.txt$ workon fresh-env(fresh-env)$ pip install -r requirements.txt[...]Successfully installed flask Werkzeug Jinja2 itsdangerous markupsafeCleaning up...(fresh-env)$

Manually manage dependency packages
As the project develops, you may find that some packages listed by pip freeze are not actually necessary for running applications. You install these packages for development purposes only. Pip freeze cannot be distinguished. it only lists installed packages. Therefore, you may need to manually manage these dependent packages. You can put the packages required to run the application into require \ _run.txt and those required to develop the application into require \ _dev.txt.
Version control
Select a version control system and use it. I recommend Git. From what I see, Git is the most popular choice for new projects over the past few days. It is very valuable to be able to delete code without having to worry about making an irreversible error. You can also free your project from the troubles of a lot of commented-out code, because you can delete them and restore them if necessary. In addition, you can back up the entire project on GitHub, Bitbucket, or your own Gitolite server.
Files outside version control
I usually put a file out of version control for two reasons: either it will make the entire project appear messy, or it is a very private key/certificate. Compiled. pyc files and virtual environments-if you do not use virtualenvwrapper for some reason-are examples of confusing projects. They do not need to be in version control because they can be re-created from the. py file and your requirements.txt file respectively.
API keys, application keys, and database certificates are examples of private keys/certificates. They should not appear in version control because their exposure will be a huge security vulnerability.
As a security-related decision, I always like to assume that my version library will become public at some time. This means to keep a secret and never assume that a security vulnerability will not be discovered. the assumption "who can guess what they can do" is called security through concealment, this is a very bad strategy.
When using Git, you can create a special file named. gitignore in your version Library. In this file, use the list wildcard to match the file name. Any file name that matches one of the modes will be ignored by Git. I recommend that you use. gitignore to control files that do not require version control. For example:

*.pycinstance/

The Instance folder is used to provide sensitive configuration variables to your applications in a safer way. I will talk more about it later.
You can read more about. gitignore here: http://git-scm.com/docs/gitignore
Debugging
1. debugging mode
Flask has a convenient function called debugging mode. To enable the debugging function, you must set debug = True in your development configuration. When it is opened, the server will automatically load when the code changes and an error will be accompanied by a stack trace and an interactive console.
Be careful! Do not use the debugging mode in the production environment. The interactive console allows arbitrary code execution and is a huge security vulnerability.
2. Flask-DebugToolbar
Flask-DebugToolbar is another amazing tool that helps debug problems in your applications. In debug mode, it places a sidebar on every page of your application. The sidebar provides information about SQL queries, log records, versions, templates, configurations, and other interesting information, making it easier to track problems.
See the debugging mode in the quick start. The official Flask documentation contains some good information about error handling, logging, and using the debugger.

Flask project configuration
When you learn Flask, the configuration looks simple. You just need to define some variables in config. py and then everything will work. When you begin to have to manage production application configurations, these simplicity begins to disappear. You may need to protect the API key and use different configurations for different environments (such as development and production environments ). In this section, we will introduce some advanced Flask functions that make management configuration easier.
Simple example
A simple application may not need any of these complex features. You may only need to put config. py in the root directory of your Repository/version library and load it in app. py or yourapp/\ _ init \ _. py.
In the config. py file, each line should contain a configuration variable value. When your application is initialized. the configuration variables in py are used to configure Flask and its extensions and they can be passed through the app. config dictionary access-for example, app. config ["DEBUG"].

DEBUG = True # Turns on debugging features in FlaskBCRYPT_LEVEL = 12 # Configuration for the Flask-Bcrypt extensionMAIL_FROM_EMAIL = "robert@example.com" # For use in application emails

The configured variable can be Flask, which can be extended or used by you. In this example, whenever we need the default "sender" in a transactional email, we can use app. config ["MAIL_FROM_EMAIL"]-for example, password reset. Place the information in a configuration variable so that it can be easily modified later.

# app.py or app/__init__.pyfrom flask import Flaskapp = Flask(__name__)app.config.from_object('config')# Now we can access the configuration variables via app.config["VAR_NAME"].

  • DEBUG: provides some convenient tools for debugging errors. This includes a Web-based Stack trace and an interactive Python console. Set to True in the development environment; set to False in the production environment.
  • SECRET \ _ KEY: this is the KEY Flask uses to sign cookies. It can also be used by extensions like the Flask-Bcrypt class. You should define it in your instance folder so that you can stay away from version control. You can read it in the next chapter.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.