Vous Avez développé une применение Python à l’Aide du рамки Фляжка . Tout se passe bien sur wortre poste et mastentant, vous vous grondez comment rendre ça, доступный au monde Entier? Avec Хероку , C’est Trivial, et c’est ce Qu’on Va Voir dans CET статья!
Heroku est Une Платформа как сервис (PAAS) Не LE, но EST Justement de délower des Applications LE Plus ICI, на NE Configurerera Aucun Servur, на N’Installera Pas Un Environmentement. На приложении Va Joye écrire atre avec python et flask, puis on va LA POUSSER SUR HROKU. На Va l’coppagner de Quelques Petits Fichiers de Configuration Pour Avvolution à Heroku Comment La Lancer. Et c’est tout!
Le, но статья de cet n’est pas de faire un tutoriel oppl sur flask et heroku. На Va Donc Faire Une Application Très Simple, Avec Une Seule Route, Juste Pour Afficher “Привет, мир”. На Va la Tester en локальный Sur Notre PC Avant de la déloverer sur heroku avec une configuration basique mais fonctionnelnel.
Креер Сон Плательская колба
Установка
La Première étape est d’Andeter Флеста. Le Plus Simple Est de Faire:
pip install flask
Si Vous Voulez Plus De Fisense Dans Votre Установка, Comme par Exemple utiliser un Виртуальная среда , Je Vous Laisse Consulter LA Section Установка DE LA Документация Officielle.
Код
En s’inspirant du QuickStart Guide Офицер, на écrit otre main.py
:
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'hello, world'
Je Suis Sous Windows, J’utilise dans un Виртуальная среда , Je Me Suis Donc Creé Un Petit Script run.bat
Pul Lancer Failement Mon Application:
set FLASK_APP=main.py .\venv\Scripts\flask run
C’est un peu urpenant quand on est abute au développement en python: on n’exécute pas Directement Notre Script avec питон
MAIS ON DIT à колба
Quel Fichier Décrit Notre Application Grâce à Une переменная D’Environnement.
Quand on ExeCute фляжка
, il démarre un servur local, par défaut sur le le port 5000, pour servir notre application:
C:\python_flask_heroku>.\venv\bin\flask run * Serving Flask app "main.py" WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Notez le Предупреждение Au Lancement: Par Défaut, Flask Используйте un servur fait pour le dévelopment mais déconceillé залить la Производство Анкет На Verra Dans La Suite Que ça Impactera notre déploiement sur heroku, puisqu’on voudra utiliser un servur d’pplication плюс адаптация.
Pour Vérifier Que Notre Application Fonctionne, IL Duft D’Ovrir Le Lien Donné Dans Les Logs Avec Firefox:
Простая, эффективная, фантазина.
Dans Ma Console, Je Vois les logs des requestes faites au servur:
127.0.0.1 - - [22/Apr/2021 11:56:20] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [22/Apr/2021 11:58:30] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [22/Apr/2021 11:58:38] "GET /try HTTP/1.1" 404 -
ICI, IL Y ЕС 2 Accès sur la Racine /
du servur qui ont fonctionné avec le code 200, ainsi qu’un accès à /пытаться
qui a échoué avec le code 404. En effet, mon приложение Définit Bien Une Route Vers /
, mais pas vers /пытаться
.
Mon Application Est Prête, Il ne Rete Plus Qu’A La Rendre, доступный Sur l’Internet mondial grâce à heroku.
Déploiement Sur Heroku
Надпись ET Установка
Pour Commencer, Il Faut Créer un Compte et Установщик L’Интерфейс En Ligne de Commande Анкет
La Commande Хероку
est désormais indesonable depuis le terminal et nous pouvons nous connecter à notre compte avec Heroku Login
Анкет Une Page Internet S’ouvre Dans Notre Navigateur Par Défaut Pour ntrer nos идентификаторы.
Креер Сон Приложение
Le Concept est Totalement Génial: Le Déploiement Condeking Juste à Faire un git push
Вер. CE GIT CODIENT LE CODE AINSI QUE DES FICHIERS DE CONFIVERURATION POUL ASPVERSKIQUER à Heroku Comment Lancer Tout çA.
На применении Déjà Une Fonctionnelle en Local, на Va Donc Créer un dépôt git avec git init
Анкет
На Cree Ensuite L ‘ Приложение Heroku , en lui donnant ou pas un nom. Dans Mon Cas, J’ai Choisi de la Nommer:
$ heroku apps You have no apps. $ heroku apps:create younup-flask Creating ⬢ younup-flask... done https://younup-flask.herokuapp.com/ | https://git.heroku.com/younup-flask.git $ heroku apps === p.gradot@younup.fr Apps younup-flask
Comme Le dépôt Essaine déjà en Local, Les пульты Сонт Ajoutées Automatiquement:
$ git remote -v heroku https://git.heroku.com/younup-flask.git (fetch) heroku https://git.heroku.com/younup-flask.git (push)
L’Adresse de Mon Application Est Déjà Доступно, Mais il n’y A Pas Grand выбрал D’atéressant …
D’Ailleurs, Elle EST Normalement Toujours доступный (Mais peut-être Qu’un Jour Je la désactiverai ….).
Конфигурация
Sur Notre PC, L’Erpréteur Python Est Install Ainsi Que Les Paquets Nécessaires. Par défaut, Heroku ne sait pas ce не номинал применение Besoin, Il faut donc lui preciser tout ça. Pour ça, il faut créer deux fichiers qu’on ajoute au dépôt git.
Le premier est Runtime.txt
Данс Лекель на Indique La версии de python Qu’on souhaite utiliser. Il y une seule ligne dans ce fichier:
python-3.9.2
Le Second Est Требования.txt
, Qui Sert à Pip
Залить Connaitre Les Paquets à Установщик :
flask gunicorn
колба
, ХОРОШО. Мейс Порукуи Онломщик
? Souvenez-Vous Plus Haut д’Он Предупреждение Lors du Lancement de Flask, Nous Conseillant de ” Вместо этого используйте производственный сервер WSGI » . Et bien C’est Percement Ce Qu’est Онломщик
:
Обилчик «Зеленый единорог» – это HTTP -сервер Python WSGI для UNIX. Это модель работника перед фвор. Сервер стрело собой в целом совместим с различными веб -структурами, просто реализованными, освещением ресурсов сервера и довольно быстрым.
Pour Avvolution à heroku Qu’il faut utiliser Онломщик
Pour Servir Notre Application Flask, на va utiliser Le Fichier Procfile
:
Приложения Heroku включают Procfile, которая указывает команды, выполняемые приложением при запуске. Вы можете использовать Procfile, чтобы объявить различные типы процессов, включая веб -сервер вашего приложения ».
Une Ligne Daud Pour Notre Procfile
:
web: gunicorn main:app
Тест en локальный
Heroku nous permet de tester en local avec la commande Хероку местный
Анкет
MalheureSement, ce n’est pas возможный Dans mon cas car Je suis sous windows et Горничный завод NE FONTICTNE PAS WINDES Анкет Si vous êtes sous linux ou macos, vous pouvez exécuter cette commande pour vérifier que tout est ok avant de passer au déploiement.
Déploiement sur l’Internet mondial
Tout est ok? Il duft de faire git commit
et git push
:
$ git push --set-upstream heroku master Énumération des objets: 6, fait. Décompte des objets: 100% (6/6), fait. Compression par delta en utilisant jusqu'à 4 fils d'exécution Compression des objets: 100% (3/3), fait. Écriture des objets: 100% (6/6), 1.18 Kio | 1.18 Mio/s, fait. Total 6 (delta 0), réutilisés 0 (delta 0), réutilisés du pack 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.9.4 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.9.2 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting flask remote: Downloading Flask-1.1.2-py2.py3-none-any.whl (94 kB) remote: Collecting gunicorn remote: Downloading gunicorn-20.1.0.tar.gz (370 kB) remote: Collecting itsdangerous>=0.24 remote: Downloading itsdangerous-1.1.0-py2.py3-none-any.whl (16 kB) remote: Collecting Werkzeug>=0.15 remote: Downloading Werkzeug-1.0.1-py2.py3-none-any.whl (298 kB) remote: Collecting click>=5.1 remote: Downloading click-7.1.2-py2.py3-none-any.whl (82 kB) remote: Collecting Jinja2>=2.10.1 remote: Downloading Jinja2-2.11.3-py2.py3-none-any.whl (125 kB) remote: Collecting MarkupSafe>=0.23 remote: Downloading MarkupSafe-1.1.1-cp39-cp39-manylinux2010_x86_64.whl (32 kB) remote: Building wheels for collected packages: gunicorn remote: Building wheel for gunicorn (setup.py): started remote: Building wheel for gunicorn (setup.py): finished with status 'done' remote: Created wheel for gunicorn: filename=gunicorn-20.1.0-py3-none-any.whl size=78917 sha256=389135bf7e57c6bee7f1675ce59482c4d7ab3500ab4debf1c633e23986c5326c remote: Stored in directory: /tmp/pip-ephem-wheel-cache-c0xwgcsz/wheels/ee/ca/72/3e9be4033d3993d4d78e2f4accdfcfff6c690921fef5ea0d57 remote: Successfully built gunicorn remote: Installing collected packages: colorama, itsdangerous, Werkzeug, click, MarkupSafe, Jinja2, flask, gunicorn remote: Successfully installed Jinja2-2.11.3 MarkupSafe-1.1.1 Werkzeug-1.0.1 click-7.1.2 colorama-0.4.4 flask-1.1.2 gunicorn-20.1.0 itsdangerous-1.1.0 remote: -----> Discovering process types remote: Procfile declares types -> web remote: remote: -----> Compressing... remote: Done: 52.6M remote: -----> Launching... remote: Released v3 remote: https://younup-flask.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done. To https://git.heroku.com/younup-flask.git * [new branch] master -> master
C’est Magnifique. Heroku nous installe l’Enterpréteur python et les paquets indiques avec Pip
, Puis Il Redémarre Notre, применение, Qui Est Mastentant Dissonible:
Издатель умен Миз à журнал
En fait, notre premier push était déjà une mise à jour. Les Mises à Joury Suivantes Se Font de la Même Façon. Imaginons Qu’on Souhaite Mettre à Jourtre версия de python, pour suivre la Рекомендация Donnée dans les logs d’stanctation: « Python выпустил обновление безопасности! Пожалуйста, рассмотрите обновление до Python-3.9.4 “. На модификации Le Fichier Runtime.txt
, на Компет , на push , et le processus d’Anstation et de déploiement regine. Cette fois, par contre, на лире:
remote: -----> Python app detected remote: -----> Found python-3.9.2, removing remote: -----> No change in requirements detected, installing from cache remote: -----> Installing python-3.9.4
Вывод
Nous Avons Vu Comment Déployer Très Simplement Notre Application Flask Sur heroku et ainsi la rendre доступен Au Monde Entier. Nous avons utilisé un compte gratuit, достаточные тесты, Des Hobbyists, Des Petites. Si vous avez des besoins плюс важные, il escience DES Versions Payantes Анкет
Heroku Supporte Plusieurs Autres Langages вне коробки et fournit дрес Начало работы по гидам Налить Чакун д’укс. Il y des astuces pour utiliser d’autres langages. Некоторые SE SERENT DE DOCKER (PAR EXEMPLE PURE FAIRE DU C# ); D’Autres utilisent le Système de BuildPacks (PAR Exemple Pour Faire du C ).
Désormais, Vous Ne Pourrez Plus Dire “Je ne sais pas Comment Mettre Mon Application Dans Le Cloud”!
Merci D’Voir Lu CET статья! Il a été posté initistement sur le Блог de Younup Анкет
Оригинал: “https://dev.to/younup/heroku-pour-deployer-votre-application-python-flask-dans-le-cloud-4b6o”