📜 ⬆️ ⬇️

Flask Mega-Tutorial Chapter 1: Hello world! (edition 2018)

blog.miguelgrinberg.com


Miguel grinberg




>>> next chapter >>>


This article is a translation of the new edition of Miguel Greenberg’s textbook. The old translation has long lost its relevance.


The author plans to complete his release in May 2018. I, for my part, will try to keep up with the translation.


For reference, below is a list of articles in this series.



The new tutorial was written in 2017, and finally it looks as if it was configured for Python 3. Compatibility issues were resolved, focus was changed to Python 3, and not Python 2 as it was in 2012 in the previous version textbook.


Unfortunately, Python 2 or 3 is not the only thing that has changed. There are also several technologies that made sense in 2012, but are now obsolete. These include:



Many of the things that have changed in these five years mainly mean that all chapters need to be revised, and most of them have undergone quite important changes.


Miguel himself believes that he has grown professionally over these five years, and thinks that he will be able to bring much more value to this textbook with this new experience. After the release of the first textbook, he spent more than a dozen conferences and released a bunch of tutorials, wrote a very successful Flask development book for a major publisher, and created several popular open source projects.


In addition, Miguel has another five years of experience as a technical blogger, as he continued to create content for his blog over the years. All this experience will be reflected in the updates that he brings in the textbook.


Read more in Miguel's blog.


VIDEO


Welcome!


You are going to go on a trip to learn how to create web applications using Python and the Flask microflash. The video above will give you an overview of the contents of this guide. In this first chapter, you will learn how to set up a Flask project. At the end of this chapter you will have a simple Flask web application running on your computer!


Note 1: If you are looking for old versions of this course, this is here .


Note 2: If suddenly you would like to speak in support of my (Miguel) work on this blog, or simply do not have the patience to wait for a week of the article, I (Miguel Greenberg) offer a full version of this guide a packed e-book or video. For more information, visit learn.miguelgrinberg.com .


All code examples presented in this tutorial are hosted on GitHub. Downloading code from GitHub will save you time, but I highly recommend entering your own code in at least the first few chapters. After you become more familiar with Flask, you can access the code directly from GitHub, in case input becomes too tedious.


At the beginning of each chapter, I will give you three GitHub links that may be useful when studying the chapter. Browse will open the GitHub repository for the microblog in the place where the changes to the chapter you are reading are collected, with the exception of any changes made in future chapters. Zip is a link to download a zip-archive, including applications and changes in the chapter. Diff - opens a graphical representation of all changes made to the chapter you are about to read.


On GitHub, the links in this chapter are: Browse , Zip , Diff .


Install python


If Python is not installed on your computer, install it. If your operating system does not have a pre-installed Python package, you can download the installer from the official Python website . If you are using Microsoft Windows with WSL or Cygwin, please note that you will not use the native version of Python for Windows, but the version compatible with Unix that you need to get from Ubuntu (if you use WSL) or from Cygwin.


To make sure your Python installation is functional, you can open a terminal window and enter python3, or if it doesn't work, just python. Here is what you should expect:


$ python3 Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> _ 

or so in cmd (Microsoft Windows command window):


 c:\cp>c:\python33\python Python 3.3.5 (v3.3.5:62cf4e77f785, Mar 9 2014, 10:37:12) [MSC v.1600 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 

The Python interpreter is now awaiting user input. In future chapters, you will learn why this interactive invitation is useful. But for now you have confirmed that Python is installed on your system. To exit the interactive prompt, you can type exit() and press Enter.


In the Python versions for Linux and Mac OS X, you can also exit the interpreter by pressing Ctrl-D .


On Windows, the exit shortcut is Ctrl-Z , then Enter.


Flask installation


The next step is to install Flask, but before I tell you about it, I want to tell you about the best methods for installing Python packages.


In Python, packages such as Flask are available in a common repository, where they can be downloaded and installed. The official Python package repository is called PyPI , which means the Python Package Index (also known as the “cheese shop”). Installing a PyPI package is very simple, because Python has a tool called pip that does the job (in Python 2.7, pip not included with Python and must be installed separately).


To install the package on your computer, you use pip as follows:


 $ pip install <package-name> 

Interestingly, this method of installing packages will not work in most cases. If your Python interpreter was installed globally for all users of your computer, it is likely that your regular user account will not receive permission to make changes to it, so the only way to execute the above command is to run it as an administrator. But even without this complication, understand what happens when you install the package, as described above. The pip tool will download the package from PyPI and then add it to your Python folder. From now on, every Python script that you have on your system will have access to this package. Imagine a situation where you finished a web application using version 0.11 of Flask, which was the most recent version of Flask at startup, but now it has been replaced by version 0.12. Now you want to run the second application for which you would like to use version 0.12, but if you replace the installed version 0.11, you risk breaking your old application. Do you see the problem? It would be ideal if you could install Flask 0.11, which will be used by your old application, and also install Flask 0.12 for your new one.


To solve the problem of supporting different versions of packages for different applications, Python uses the concept of virtual environments. A virtual environment is a complete copy of the Python interpreter. When you install packages in a virtual environment, the system-wide Python interpreter is not affected, only a copy. Thus, the decision to have complete freedom to install any versions of your packages for each application is to use a different virtual environment for each application. Virtual environments have the added advantage that they belong to the user who creates them, so they do not need an administrator account.


Let's start by creating a directory in which the project will live. I am going to name this microblog directory since this is the name of the application:


 $ mkdir microblog $ cd microblog 

If you are using the Python 3 version, it includes support for the virtual environment, so all you need to do to create it is:


 $ python3 -m venv venv 

With this command, Python will launch the venv package, which creates a virtual environment called venv . The first venv in the command is the name of the Python virtual environment package, and the second is the name of the virtual environment that I will use for this particular environment. If you think this is confusing, you can replace the second venv different name that you want to assign to your virtual environment. In general, I create my own virtual environments with the name venv in the project directory, so whenever I connect to a project, I find its corresponding virtual environment.


Please note that on some operating systems you may need to use python instead of python3 in the above command. Some installations use python for releases of Python 2.x and python3 for releases of 3.x, while others display python in releases of 3.x.


When the command completes, you will have a directory named venv where the virtual environment files are stored.


If you are using any version of Python older than 3.4 (including release 2.7), virtual environments are not natively supported. For these versions of Python, you need to download and install a third-party virtualenv tool before creating virtual environments. After virtualenv installed, you can create a virtual environment with the following command:


 $ virtualenv venv 

or so


 $ python virtualenv.py venv 

Note: I have several versions of Python installed. I am using Python3.3. In my case, I had to enter a string like this:


 C:\microblog>c:\Python33\python.exe c:\Python33\Lib\site-packages\virtualenv.py venv 

In the received message you can see that pip and a number of packages are installed:


 Using base prefix 'c:\\Python33' New python executable in C:\microblog\venv\Scripts\python.exe Installing setuptools, pip, wheel...done. 

Regardless of the method you used to create it, you created your own virtual environment. Now you need to tell the system that you want to use it by activating it. To activate a new virtual environment, use the following command:


 $ source venv/bin/activate (venv) $ _ 

If you use cmd (Microsoft Windows Command Prompt window), the activation command is slightly different:


 $ venv\Scripts\activate (venv) $ _ 

When you activate a virtual environment, the terminal's session configuration changes so that the Python interpreter stored inside it becomes what is called when you enter python . In addition, the name of the activated virtual environment is included in the terminal request. Changes made to a terminal session are temporary and private for this session, so they will not be saved when the terminal window is closed. If you simultaneously work with several terminal windows, it is perfectly obvious that each of them has different virtual environments.


Now that you have created and activated a virtual environment, you can finally install Flask into it:


 (venv) C:\microblog>pip install flask Collecting flask Using cached Flask-0.12.2-py2.py3-none-any.whl Requirement already satisfied: click>=2.0 in c:\python33\lib\site-packages (from flask) Requirement already satisfied: Werkzeug>=0.7 in c:\python33\lib\site-packages (from flask) Requirement already satisfied: Jinja2>=2.4 in c:\python33\lib\site-packages (from flask) Requirement already satisfied: itsdangerous>=0.21 in c:\python33\lib\site-packages (from flask) Requirement already satisfied: markupsafe in c:\python33\lib\site-packages (from Jinja2>=2.4->flask) Installing collected packages: flask Successfully installed flask-0.12.2 (venv) C:\microblog> 

If you want to verify that Flask is installed in your virtual environment, you can run the Python interpreter and import Flask into it:


 (venv) C:\microblog>python Python 3.3.5 (v3.3.5:62cf4e77f785, Mar 9 2014, 10:37:12) [MSC v.1600 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import flask >>> 

If this import does not give you any errors, you can congratulate yourself, since Flask installed and ready to use.


Flask application "Hello world"


If you go to the Flask website , you are greeted by a very simple sample application with five lines of code. Instead of repeating this trivial example, I will show you a little more complicated one, which will give you a good basic structure for writing large applications.


The application will exist as a package.


Note of Translator: A package is a collection of modules.


In Python, the subdirectory containing the __init__.py file is considered a package and can be imported. When you import a package, __init__.py executes and determines which characters provide the package to the outside world.


Let's create a package called app in which the application will be placed. Make sure you are in the microblog directory, and then run the following command:


 (venv) $ mkdir app 

__init__.py for the application package will contain the following code:


 from flask import Flask app = Flask(__name__) from app import routes 

The script above simply creates an application object as an instance of the Flask class imported from the flask package. The variable __name__ passed to the Flask class is a predefined Python variable that is specified by the name of the module in which it is used. Flask uses the location of the module, provided here as a starting point, when it needs to load related resources, such as template files, which I will cover in Chapter 2 . For all practical purposes, passing __name__ almost always set up flask in the right direction. The application then imports the routes module, which does not yet exist.


One aspect that may seem confusing at first is that there are two objects named app . The application package is determined by the application directory and the __init__.py script and is specified in the application import instructions. The app variable is defined as an instance of the Flask class in the __init__.py script, which makes it part of the application package.


Another feature is that the routes module is imported at the bottom and not at the top of the script, as is always the case. Bottom import is a workaround for cyclical imports, which is a common problem when using Flask applications. You will see that the routes module must import the application variable defined in this script, so by placing one of the mutual imports at the bottom, you will avoid the error that arises from the reciprocal links between these two files.


So what is included in the routes module? routes are different URLs that the application implements. In Flask, application route handlers are written as Python functions, called browsing functions. The browsing functions are mapped to one or more route URLs, so Flask knows which logic to execute when the client requests this URL.


Here is your first browsing function that you need to write in the new module named app/routes.py :


 from app import app @app.route('/') @app.route('/index') def index(): return "Hello, World!" 

This viewing function is actually quite simple; it simply returns the greeting as a string. The two strange lines @app.route over the function are the decorators, a unique feature of the Python language. The decorator changes the function that follows it. Common template with decorators - use them to register functions as callbacks for certain events. In this case, the @app.route decorator creates a link between the URL specified as an argument and the function. In this example, there are two decorators that associate the URLs / and /index with this function. This means that when a web browser requests one of these two URLs, Flask will call this function and pass the return value back to the browser as a response. If it seems to you that this does not make sense yet, it will not be long until you start this application.


To complete the application, you need to create a python script at the top level that defines an instance of the Flask application. Let's call this script microblog.py and define it as one line that imports an instance of the application:


 from app import app 

Remember the two app objects? Here you can see both together in one sentence. The Flask application instance is called app and is included in the app package. from app import app imports the app variable included in the app package. If you find this confusing, you can rename either the package or the variable to something else.


To make sure that you are doing everything right, below is a diagram of the project structure:


 microblog/ venv/ app/ __init__.py routes.py microblog.py 

Believe it or not, the first version of the application is complete! Before launching it, Flask needs to be told how to import it by setting the FLASK_APP environment FLASK_APP :


 (venv) $ export FLASK_APP=microblog.py 

If you are using Microsoft Windows, use the 'set' command instead of the 'export' command in the command above.


Are you ready to be shocked? You can run your first web application with the following command:


 (venv) $ flask run * Serving Flask app "microblog" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) 

Note: I was shocked because I got an encoding error. If you have a version of Python older than 3.6 you are most likely in for a surprise. Type:


 Syntax Error: (unicode error) 'utf-8' codec can't decode byte 0xcf in position 0: invalid continuation byte: 

In my case, the Cyrillic PC characters are to blame for the computer name. Replaced with PK and it worked. The socket module is to blame


 (venv) C:\microblog>python Python 3.3.5 (v3.3.5:62cf4e77f785, Mar 9 2014, 10:37:12) [MSC v.1600 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from socket import gethostbyaddr >>> gethostbyaddr('127.0.0.1') ('Acer-PK', [], ['127.0.0.1']) >>> 

It really worked:


 (venv) C:\microblog>set FLASK_APP=microblog.py (venv) C:\microblog>flask run * Serving Flask app "microblog" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) 


What to write in Russian "Hello, World!" need to adjust
routes.py module


Add line # -*- coding: utf-8 -*-


 # -*- coding: utf-8 -*- from app import app @app.route('/') @app.route('/index') def index(): return ", !" 


When you finish playing with the server, you can just press Ctrl-C to stop it.


Congratulations, you have made the first big step to becoming a web developer!


>>> next chapter >>>


')

Source: https://habr.com/ru/post/346306/


All Articles