Installation and creating the environment
For Max OS users, the first thing you need to do is to install virtualenv
|
|
Once we have finished installing virtualenv, we can create our own environment. For example:
|
|
To active the corresponding environment,
|
|
To deactive the environment,
|
|
If you are not using other OS, take a look at the flask documentation. http://flask.pocoo.org/docs/0.12/installation/#installation
pip freeze
requirement.txt is commonly used in Flask to list all the dependent packages. It can be generated by pip freeze > requirement.txt
and to install all the packages, you only need to run pip install -r requirements.txt
Note: When you freeze or install the packages, make sure you are in the correct virtual environment.
pip install flask-script
Flask-Script extension provides support for writing external script in Flask. This includes running a development server, a customised python shell, scripts to set up your database, cronjobs, and other command-line tasks that belong outside the web application itself.
Flask-Script works in a similar way to Flask itself. You define and add commands that can be called from the command line to a Manager instance:
|
|
Once you define your script commands, you can then run them on the command line:
|
|
The second argument hello
is same as the function name.
Quickstart
Save the following content as “Hello.py” inside the flaskPlayground folder.
|
|
Then run the following command in the terminal:
|
|
Now, we start our first flask server. :P
Error Handling for 404
If the user type the wrong url, we should tell him that it is not found, but in another case, for example:
|
|
If the user type /author/123
, even if the author does not exist…. It should also render that page. Here is the solution: we can pre-define a list to store all the available author names, and then
|
|
And it will force to redirect to 404 Not found page.
Also, we can check the input type for example: change /author/<authors_last>
to /author/<string: authors_last>
The following code is how to handle the 404 not found exception:
|
|
Render a html file
Note that the default path is /templates/
. So make sure that all the files are stored in that directory, or you need to edit the default path.
|
|