I made a Nyanko tweet form with Python, Flask and Heroku

I used Flask and Heroku to create a simple post form.

(1) Output image

The goal was to create a simple posting form like the one below. スクリーンショット 2020-03-01 21.23.24.png Enter "Nya Nya" in the tweet content and "Tama" in the tweeted cat, and press the send button. スクリーンショット 2020-03-01 21.25.01.png It will be posted like this.

(2) Set up a virtual environment

Create a directory called my_form on desktop, move to the directory and set the virtual environment. Start a virtual environment.

python3 -m venv .
source bin/activate

(3) Install the necessary framework and WEB server

Install flask and gunicorn.

pip install flask
pip install gunicorn

(4) Prepare the necessary directories and files (.py .html)

Create form.py in my_form directory, Also, create a templates directory and index.html and layout.html (in the templates directory) in the my_form directory.

(4) Describe form.py

Describe the following.

form.py


from flask import Flask,request,render_template
app = Flask(__name__)


@app.route("/")
def show():
    return render_template("index.html")


@app.route("/result",methods=["POST"])
def result():
    article = request.form["article"]
    name = request.form["name"]
    return render_template("index.html",article=article,name=name)

By importing render_template, the environment to use Jinja2 was prepared. The Jinja2 template engine calls the html template (here, index.html).

First, for the processing of @ app.route ("/"), call index.html with Jinja2. In particular,

return render_template("index.html" 〜)

And.

Next, regarding the processing of @ app.route ("/ result", method = [" POST"]), by importing reuest, the data entered in the form can be retrieved on the called html side. For example, for article, by setting article = request.form ["article"], the content entered in the form on the index.html side (the form name attribute on the index.html side is set to "article"). (Assumed) can be taken out. As for methods, the form on the index.html side is sent by the POST method this time, so it was set to [POST]. Transmission by the GET method will be described later.

article = request.form["article"]

The extracted article and the contents of name are returned to index.html as return render_template. At that time, assign values to each of the argument article and name.

return render_template("index.html",article=article,name=name)

methods is POST

@app.route("/result",methods=["POST"])

(5) Describe layout.html

Create a common html so that maintenance of the common part will be easy even if the template part increases.

layout.html


<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>Nyanco Form</title>
        <style>body {padding: 10px;}</style>
    </head>
    <body>
        {% block content %}
        {% endblock %}
    </body>
</html>

Individual contents (index.html) can be fitted in the following parts.

{% block content %}

(6) Describe index.html

index.html


{% extends "layout.html" %}
{% block content %}
<h1>Nyanko Tweet Form</h1>

<form action="/result" method="post">
      <label for="article">Content of tweet</label>
      <input type="text" name="article">
      
      <p></p>
      
      <label for="name">Tweeted cat</label>
      <input type="text" name="name">
      <button type="submit">Send</button>
</form>

<p></p>

<p>Tweet content/{{ article }}</p>
<p>Tweeted cat/{{ name }}</p>
{% endblock %}

The contents from {% block content%} to {% endblock%} are inserted in the part of layout.html. The name attribute of input is "article".

 <input type="text" name="article">

The destination address is / result, and the content entered in the form is sent by the POST method.

<form action="/result" method="post">

(7) Try to start in the local environment

Try starting flask as follows.

 FLASK_APP=form.py flask run
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

If you paste the http: // ~ part into your browser,

スクリーンショット 2020-03-01 22.14.45.png If it appears, it is successful.

(8) Difference between POST method and GET method

I used the POST method this time, but I'll also note the GET method. In the case of the POST method, when you submit the form, スクリーンショット 2020-03-01 22.18.21.png And when you look at the browser address, スクリーンショット 2020-03-01 22.18.10.png It has become. On the other hand, if you use the GET method, modify form.py and index.html as follows.

form.py


from flask import Flask,request,render_template
app = Flask(__name__)


@app.route("/")
def show():
    return render_template("index.html")


@app.route("/result",methods=["GET"])
def result():
    article = request.args.get("article")
    name = request.args.get("name")
    return render_template("index.html",article=article,name=name)

index.html


{% extends "layout.html" %}
{% block content %}
<h1>Nyanko Tweet Form</h1>

<form action="/result" method="get">
      <label for="article">Content of tweet</label>
      <input type="text" name="article">

      <p></p>

      <label for="name">Tweeted cat</label>
      <input type="text" name="name">
      <button type="submit">Send</button>
</form>

<p></p>

<p>Tweet content/{{ article }}</p>
<p>Tweeted cat/{{ name }}</p>
{% endblock %}

When I send it and look at the browser address, スクリーンショット 2020-03-01 22.24.51.png The GET method is designed to add the data to be sent to the end of the address. Therefore, what kind of data will be seen by other people, so it is used for applications such as search. It is necessary not to use it for forms that enter passwords.

(9) Deploy on Heroku

The details of deploying to Heroku are as described in the following article, so I will only use the essence and omit the detailed explanation. https://qiita.com/nooonchi/items/a7ea7c7a12c56ab8e901

Log in to Heroku and create an app on Heroku

heroku login

The app name is cat-form.

Heroku create cat-form

Initialize the directory my_form and

git init

Link Heroku with your local environment

heroku git:remote -a cat-form

Create requirements.txt in the directory my_form and

pip freeze > requirements.txt

Create a Prockfile in the directory my_form and enter the following: At this time, one blank is required before g, and the form before: app means the form of form.py, so be careful.

web: gunicorn form:app --log-file -

add and

git add .

This time, commit with the name the-first,

git commit -m'the-first'

Push to Heroku.

git push heroku master

Finally,

heroku open

Then it's done. スクリーンショット 2020-03-01 21.23.24.png

(10) Conclusion

In the future, I would like to develop this and challenge the bulletin board.

Postscript

--Introduced Flask-Bootstap to this form (2020.3.2) I made a Nyanko tweet form with Python, Flask and Heroku + Flask-Bootstrap introduced

Recommended Posts

I made a Nyanko tweet form with Python, Flask and Heroku
I made a LINE BOT with Python and Heroku
I made a Mattermost bot with Python (+ Flask)
I made a fortune with Python.
I made a daemon with Python
I made a simple book application with python + Flask ~ Introduction ~
I made a character counter with Python
I made a Hex map with Python
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a neuron simulator with Python
I made a weather forecast bot-like with Python.
I made a GUI application with Python + PyQt5
I made a Twitter fujoshi blocker with Python ①
[Python] I made a Youtube Downloader with Tkinter.
Launch a web server with Python and Flask
I made a bin picking game with Python
I made a Twitter BOT with GAE (python) (with a reference)
I made a Christmas tree lighting game with Python
I made blackjack with python!
I made a net news notification app with Python
[ES Lab] I tried to develop a WEB application with Python and Flask ②
I made a Python3 environment on Ubuntu with direnv.
I made a python text
I made blackjack with Python.
I made wordcloud with Python.
I made a program to convert images into ASCII art with Python and OpenCV
I made a web application that maps IT event information with Vue and Flask
How to deploy a web app made with Flask to Heroku
I made a simple typing game with tkinter in Python
I made a package to filter time series with python
I made LINE-bot with Python + Flask + ngrok + LINE Messaging API
(Failure) Deploy a web app made with Flask on heroku
Create Heroku, Flask, Python, Nyanko bulletin boards with "csv files"
I made a puzzle game (like) with Tkinter in Python
I made a Chatbot using LINE Messaging API and Python
SNS Python basics made with Flask
I made a Line-bot using Python!
I liked the tweet with python. ..
I played with PyQt5 and Python3
I made a server with Python socket and ssl and tried to access it from a browser
I made a library to easily read config files with Python
[Python3] I made a decorator that declares undefined functions and methods.
I made a package that can compare morphological analyzers with Python
Build a detonation velocity website with Cloud Run and Python (Flask)
I made a lot of files for RDP connection with Python
[Python] I made an image viewer with a simple sorting function.
I tried to make a periodical process with Selenium and Python
I made a shuffle that can be reset (reverted) with Python
I made a poker game server chat-holdem using websocket with python
I made a segment tree with python, so I will introduce it
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
I made a chatbot with Tensor2Tensor and this time it worked
I tried linebot with flask (anaconda) + heroku
I made a payroll program in Python!
I drew a heatmap with seaborn [Python]
POST variously with Python and receive with Flask
A memo with Python2.7 and Python3 on CentOS
I tried a functional language with Python
I installed and used Numba with Python3.5