Python. Настраиваем Pycharm для работы с Flask
Flask — это мини-фреймворк для разработки веб-приложений на Python, он прост и удобен в использовании. Сегодня я покажу вам как настроить Pycharm Community Edition от Jetbrains для работы с этим фреймворком. Зачем использовать именно IDE Pycharm? Да потому, что Pycharm можно скачать совершенно бесплатно и эта IDE очень удобная и самая используемая в мире разработки Python. Скачать Pycharm вы можете на официальном сайте компании Jetbrains по этой ссылке.
Шаг первый. Создадим первое приложение на Flask
Откройте Pycharm, нажмите New Project и сохраните созданный проект в своей директории. При создании вам нужно выбрать версию интерпретатора Python, либо это 2.7 или 3.х, в моем случае я выбрал последнею версию Python 3.7.

Шаг второй. Устанавливаем рабочее окружение для Flask
После того как вы создали проект, вам надо настроить под него окружение. Первым шагом вы должны создать файл с расширением типа *.py. Допустим пускай это будет main.py. Для того что бы вам это сделать, вы должны кликнуть по правой кнопкой мыши по директории проекта в IDE и выбрать пункт New и далее Python File, далее вам надо вести название вашего файла и сохранить его.

Шаг третий. Работа создание первого файла
В созданном вами файле вам надо написать следующий код. Это довольно простая программа которая отдает всего лишь одно предложение «This is a Flask». Да это будет вашей первой программой, которую вы создадите при помощи фреймворка Flask.
from flask import Flask app = Flask(name)
@app.route('/') def index(): return 'this is a Flask'
app.run('0.0.0.0:8000', debug=True)
Запустите данный код просто нажав правой кнопкой мыши и выбрав пункт меню Run ‘app’ или используйте сочетание клавиш клавиатуры Ctrl+Shift+F10. Если после этого ваш скрипт выдал в консоли Pycharm, что то подобное то значит вы все сделали правильно.
Если в консоли есть ошибки и скрипт не работает, то надо убедиться, что интерпретатор видет пакет Flask. В Pycharm вы можете просто установить пакет просто кликнув в меню на пункт File > Settings > Project > Project Interpreter и установить пакет Flask. Если пакета в списке нет, то вы можете установить его самостоятельно, просто нажав зеленый крестик в правом верхнем углу IDE.

После этого вам надо открыть браузер и вбить в него урл на который указан в приложении Flask, в нашем случае это 0.0.0.0:8000 и в окне браузера должна появиться надпись которую мы указали в скрипте выше.

Поздравляем! Это ваше первое приложение, которое вы написали при помощи это мини-фреймворка Flask.
Creating a Flask Project
Flask project in intended for productive development of the Flask applications. PyCharm takes care of creating the specific directory structure, and settings.
Create a Flask project
- In the main menu, go to File | New Project , or click the New Project button in the Welcome screen.

- In the New Project dialog, do the following:
- Select Flask as the project type.
- Specify the project location.
- Select Create Git repository to put the project under Git version control.
- If you want to proceed with the Project venv or Base conda interpreter, select the corresponding option and click Create . Project venv PyCharm creates a virtualenv environment based on the system Python in the project folder. If you don’t have the desired Python version in your system, you can download and install it.
This feature is available only on Windows and macOS. Base conda PyCharm configures conda base environment as the project interpreter. To configure an interpreter of other type or to use an existing environment, select Custom environment . The following steps depend on your choice:

- Select the Python version from the list.
- Normally, PyCharm will detect conda installation. Otherwise, specify the location of the conda executable, or click to browse for it.
- Specify the environment name.

- Specify the location of the new virtual environment in the Location field, or click and browse for the desired location in your file system. The directory for the new virtual environment should be empty.
- Choose the base interpreter from the list, or click and find the desired Python executable in your file system. If you don’t have the desired Python version in your system, you can download and install it.
This feature is available only on Windows and macOS. - Select the Inherit global site-packages checkbox if you want all packages installed in the global Python on your machine to be added to the virtual environment you’re going to create. This checkbox corresponds to the —system-site-packages option of the virtualenv tool.
- Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in PyCharm.

Choose the base interpreter from the list, or click and find the desired Python executable in your file system.
If you don’t have the desired Python version in your system, you can download and install it.

This feature is available only on Windows and macOS.
If you have added the base binary directory to your PATH environmental variable, you don’t need to set any additional options: the path to the pipenv executable will be autodetected.
If the pipenv executable is not found, follow the pipenv installation procedure to discover the executable path, and then specify it in the dialog.

Choose the base interpreter from the list, or click and find the desired Python executable in your file system.
If you don’t have the desired Python version in your system, you can download and install it.

This feature is available only on Windows and macOS.
If PyCharm doesn’t detect the poetry executable, specify the following path in the dialog, replacing jetbrains with your username:
Python — делаем приложение на Flask в локальной среде
Admin
04.10.2020 , обновлено: 12.01.2021
Flask
Любая разработка приложения на Python начинается из локальной среды. Создадим проект (приложение или сайт) на микрофреймворке Flask для последующей транспортировки его на сервер. Пример будет дан для Mac OS, но для Windows примерно все то же самое.
Этот материал из цикла статей по разработке сайтов на python: от локальной разработки до развертывания на удаленном сервере.
Создание проекта на Flask
Для работы с python есть несколько программ IDE. Я отдаю предпочтение PyCharm и далее будут примеры с ним.
Создать виртуальную среду разработки можно через PyCharm или самостоятельно. Ниже приведены 2 варианта.
а) Через PyCharm
Создание проекта через PyCharm:

В этом случае PyCharm сам установит интерпретатор. Но иногда интерпретатор приходится в настройках указывать самостоятельно, потому что PyCharm может его не видеть. Такое случается после обновления python на новые версии.
Кроме этого, в процессе создания проекта на PyCharm он сам установит необходимые файлы и зависимости для Flask.
б) Самостоятельно
Создадим сами виртуальное окружение для python:
python3 -m venv venv
Зайдем в виртуальное окружение:
Run/Debug Configuration: Flask Server
Use this dialog to create run/debug configuration for Flask server and customize the way PyCharm executes your Flask application.
See Creating web applications with Flask for more details on using Flask in PyCharm.
Select Run | Edit Configurations from the main menu, then click and select the Flask template.

Fill in the following parameters:
Configuration tab
Module name/Script path/Custom
Choose one of the following methods to construct and pass the FLASK_APP variable to Flask:
- Module name – by using a Python module name and a Flask class instance.
- Script path – by using a path to a Python file.
- Custom – by using an arbitrary combination of paths, modules, and Flask class instances.
For more information about the FLASK_APP variable, refer to Flask CLI documentation.
Depending on the selected Target type , you can specify the following values:
- Path to the Python file, for example, /Users/jetbrains/MyFlaskProject/app.py . You can type in the path or click the button to locate the file in the project structure.
- Name of the module in the Flask project, for example, access_management . You can type in the module name or click the button to search the target module by its name or to locate it in the project structure.
- Custom combination of modules, scripts, and Flask class instances, for example, access_management.access:app2 , where:
- access_management – the module name
- access – the target file in the module
- app2 – the Flask class instance in access .
The target Flask class instance to be executed. This value will be put into the FLASK_APP variable during the execution. For example, you’ve declared the following instance of the Flask class in your application:
Then you can add app into the Application field. It is typically used for the Module name target type. For Script path , the Application field is enabled only for the Flask version 0.13 and later. The field is disabled for the Custom target type, because you can specify the required instance in the combination added to the Target field.
Parameters of the flask run command.
—host – the IP address of the web server to run your Flask application on. The default value is ‘127.0.0.1’. To make your web server externally visible, use the ‘0.0.0.0’ value for this parameter.
—port – the port of the web server. The default value is 5000 or it is the port number set in the SERVER_NAME config variable.
Example: —host=127.0.0.2 —port=1234 .
An environment variable set to one of possible environments. The default value is ‘development’.
Select this checkbox to enable the built-in Flask debug mode. With this mode, the development server will be automatically reloaded on any code change enabling continuous debugging. For more information about Flask debugger, refer to Flask Debug Mode.
Click this list to select one of the projects, opened in the same PyCharm window, where this run/debug configuration should be used. If there is only one open project, this field is not displayed.
This field shows the list of environment variables. If the list contains several variables, they are delimited with semicolons.
By default, the field contains the variable PYTHONUNBUFFERED set to 1. To fill in the list, click the browse button, or press Shift+Enter and specify the desired set of environment variables in the Environment Variables dialog.
To create a new variable, click , and type the desired name and value.
You might want to populate the list with the variables stored as a series of records in a text file, for example:
Variable1 = Value1 Variable2 = Value2
Just copy the list of variables from the text file and click Paste () in the Environmental Variables dialog. The variables will be added to the table. Click Ok to complete the task. At any time, you can select all variables in the Environment Variables dialog, click Copy , and paste them into a text file.
Select one of the pre-configured Python interpreters from the list.
Note that you can select a remote interpreter as well as the local one.
In this field, specify the string to be passed to the interpreter. If necessary, click , and type the string in the editor.
Specify a directory to be used by the running task.
- When a default run/debug configuration is created by the keyboard shortcut Control+Shift+F10 , or by choosing Run from the context menu of a script, the working directory is the one that contains the executable script. This directory may differ from the project directory.
- When this field is left blank, the bin directory of the PyCharm installation will be used.
Add content roots to PYTHONPATH
Select this checkbox to add all content roots of your project to the environment variable PYTHONPATH;
Add source roots to PYTHONPATH
Select this checkbox to add all source roots of your project to the environment variable PYTHONPATH;
Logs tab
Use this tab to specify which log files generated while running or debugging should be displayed in the console, that is, on the dedicated tabs of the Run or Debug tool window.
Select checkboxes in this column to have the log entries displayed in the corresponding tabs in the Run tool window or Debug tool window.
The read-only fields in this column list the log files to show. The list can contain:
- Full paths to specific files.
- Aliases to substitute for full paths or patterns. These aliases are also displayed in the headers of the tabs where the corresponding log files are shown. If a log entry pattern defines more than one file, the tab header shows the name of the file instead of the log entry alias.
Select this checkbox to have the previous content of the selected log skipped.
Save console output to file
Select this checkbox to save the console output to the specified location. Type the path manually, or click the browse button and point to the desired location in the dialog that opens.
Show console when a message is printed to standard output stream
Select this checkbox to activate the output console and bring it forward if an associated process writes to Standard.out.
Show console when a message is printed to standard error stream
Select this checkbox to activate the output console and bring it forward if an associated process writes to Standard.err.
Click this button to open the Edit Log Files Aliases dialog where you can select a new log entry and specify an alias for it.
Click this button to edit the properties of the selected log file entry in the Edit Log Files Aliases dialog.
Click this button to remove the selected log entry from the list.
Click this button to edit the select log file entry. The button is available only when an entry is selected.
Common settings
When you edit a run configuration (but not a run configuration template), you can specify the following options:
Specify a name for the run configuration to quickly identify it among others when editing or running.
Allow multiple instances
Allow running multiple instances of this run configuration in parallel.
By default, it is disabled, and when you start this configuration while another instance is still running, PyCharm suggests stopping the running instance and starting another one. This is helpful when a run configuration consumes a lot of resources and there is no good reason to run multiple instances.
Store as project file
Save the file with the run configuration settings to share it with other team members. The default location is .idea/runConfigurations . However, if you do not want to share the .idea directory, you can save the configuration to any other directory within the project.
By default, it is disabled, and PyCharm stores run configuration settings in .idea/workspace.xml .
Toolbar
The tree view of run/debug configurations has a toolbar that helps you manage configurations available in your project as well as adjust default configurations templates.