Getting Started with Flask with Azure Web Apps

This article is Request! Tips for developing on Azure using Python![PR] This is the article on the 25th day of Microsoft Japan Advent Calendar 2020. I thought I had time, so I went to the end, but I was unexpectedly busy ...

Introduction

When you make a useful tool in Python, why don't you want other people to use it? If you use Azure, you can easily create a web application. I started touching Azure around March and realized how easy it is to make it, so I will summarize those procedures. Also, there were few articles made with Flask, so I will write it.

Target audience

--People who want to use Azure Web Apps --You can use Python. --You have a GitHub, Azure account. -(If you look it up on Google, you'll see a lot) --People who want to create web applications with Flask

What to make

The outline of the application to be created this time is Enter in the html text box → press the button → perform processing → display html I will make an application called.

image.png

Flask application creation

First, install Flask in the environment where Python is installed.

pip install flask

If you can install Flask, the environment construction is complete.

Write html

The file is created in templates/page.html.

templates/page.html


<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>Page</title>
    </head>
    <body>
      <form action = "/" method = "POST">
         <H1>Application to display the name</H1>
         <h1>input</h1>
         <textarea type="text" name="name" placeholder="name"></textarea>
         <br>
         <input type="submit" value="Run">
      </form>
      <h1>output</h1>
      <p>{{text}}</p>
   </body>
</html>

There are many unnecessary parts, but I put a name in the text box and made a place to output. The part specific to Flask and dynamic sites is the double brackets {{text}}. The result is output here.

Backend edition

Next, let's create a backend. This time, the input is displayed as it is.

The file is created in application.py. As I will explain later, when hosting on Azure, the first thing that is loaded is ** application.py **. (The file name is surprisingly important!) (In the Flask sample, it was app.py, so I have not confirmed it, but that may be okay.)

application.py


from flask import Flask,render_template,request

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def main_page():
    if request.method == 'GET':
        text = "The result is output here"
        return render_template("page.html",text=text)
    elif request.method == 'POST':
        name = request.form["name"]
        text = "Hello" + name + "Mr."
        return render_template("page.html",text=text)

##Run
if __name__ == "__main__":
    app.run(debug=True)
python3 application.py

Run it and go to http://127.0.0.1:5000/ and you'll see it displayed.

First, we are importing Flask, render_template, request from the Flask library.

After that, I am creating an application with ``` app = Flask (__ name__)` ``. And finally, I'm writing the code for execution.

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


 So, I am creating an endpoint.
 In this case, it is created under the condition of the GET method on the/page. You can change the behavior by listing only POST or both GET and POST.

 The function defined below it is the function to be executed.

#### **`python`**
```if request.method == 'get'

 So, it describes the operation when it was a GET method.
 If it was GET, text = "results will be output here" will be passed to page.html.

 Now that you have the information you entered, all you have to do is pass the value to html.

#### **`return render_template("page.html",text=text)`**
```html",text=text)

Render_template (html name, argument to pass) as return value It will be in the form of. When executed, it will be as follows.

image.png

On the other hand, if it is sent by POST

text = request.form["name"]


 I am getting the information sent from the text box in. name is the name of the id of the textarea defined in the html file.

 As with GET, the text is put in page.html and displayed.

 You have now created a simple application locally. Now let's get ready to deploy to Azure.

# Give code to GitHub
 This time, I want to use GitHub Actions when deploying to Azure, so I will deploy the code to GitHub. Also, list the required libraries in requirements.txt


#### **`requirements.txt`**
```txt

Flask==1.0.2

In requirements.txt, describe the library that is always installed by pip etc. The description is ``` library name (name at the time of installation) == version` ``. If you omit the version name, the latest version will be installed.

Create a branch on GitHub and commit. There is a lot of information on the net about how to do this, so you can find it by doing a Google search. Personally, I think GitHub Desktop is easy to understand because it can be operated with GUI.

https://github.com/kurikinton105/AzureAppSample This is the branch I created this time.

Deploy to Azure

Go to the Azure portal (https://portal.azure.com/). image.png

Search for a service or select "App Servise" from the Azure service.

image.png

Create a new instance from Add.

image.png

The name of the instance details will be the URL at the time of hosting. Choose Python as your runtime stack. You can choose between 3.7 and 3.8. You can select Japan as the region, but it may not be available for free, so I am using the one displayed by default.

Finally, press "Confirm and Create" at the bottom. 39e05ac5e4e5401f45ffba5fa278d0df-png.png

Press "Create". After waiting for a while, when the deployment is completed, it is complete.

Press Go to Resource to deploy the GitHub code. スクリーンショット 2020-12-25 15.32.20.png

When you press it, various things will appear, so select "GitHub" image.png Select GitHub Actions and press Continue. image.png Select the branch you just created. image.png Press Done to finish. image.png

Wait about 5 minutes and you'll see it deployed. You can see the deployment progress by going to Actions in the GitHub repository.

image.png

If there are any changes in the future, this workflow will work and automatically deploy when you commit to GitHub. It's that easy!

I don't know how long it will remain, but it's the result of the deployment. https://azureappsamle-yama.azurewebsites.net/

This way you can easily deploy your Flask application using Azure Web App! Why don't you try deploying the application that you have been using for yourself? I made the one that automatically generates references from URLs and text summarization app. However, the free server is Yowayowa, so it may be a little slow.

Load images and CSS with Flask

Another stumbling block in Flask is that the file paths are a bit more complicated. Images and CSS are stored in the ** static/** folder For example, when displaying Qiita Icon qiita-qiita-jobs-favicon.png on page.html, place the image in `static/qiita-qiita-jobs-favicon.png```. Then, add ``` <img src ="/static/qiita-qiita-jobs-favicon.png ">` to page.html to display it.

image.png

Next step

It seems unusual to use render_template to return the HTML file once, so let's create the front end and back end separately. As for the front end, Azure Static Apps was recently released, so it would be nice to be able to use it while using it. (Reference: Deploy a website to Azure Static Web Apps easily even for beginners of the front end) The back end is created by converting what is returned by return into JSON format. Also, I think that it is possible to develop a backend with REST API (and also create a document using swagger etc.).

It would be great if you could tell that you can use a server in Azure and create a web application unexpectedly easily. I also registered with Azure in March and started studying for the first time, and now that it's easy to use, I've even been to a hackathon, so I thought it would be helpful for those people.

References

--Official document - https://docs.microsoft.com/ja-jp/azure/app-service/quickstart-python --Official sample - https://github.com/Azure-Samples/python-docs-hello-world --Sample to put Python Flask web app on Azure App Service (Web App) | Qiita - https://qiita.com/567000/items/492ee5dd2974d3cf2094

Recommended Posts

Getting Started with Flask with Azure Web Apps
Getting Started with Python Web Applications
Getting Started with Python Web Scraping Practice
Getting Started with Python Web Scraping Practice
Getting Started with Heroku, Deploying Flask App
Getting started with Android!
1.1 Getting Started with Python
Getting Started with Golang 2
Getting started with apache2
Getting Started with Golang 1
Getting Started with Python
Getting Started with Django 1
Getting Started with Optimization
Getting Started with Golang 3
Getting Started with Numpy
Getting started with Spark
Getting Started with Python
Getting Started with Pydantic
Getting Started with Golang 4
Getting Started with Jython
Getting Started with Django 2
Flask can't be RESTful with azure API Apps
Translate Getting Started With TensorFlow
Getting Started with Python Functions
Getting Started with Tkinter 2: Buttons
Getting Started with Go Assembly
Getting Started with PKI with Golang ―― 4
Getting Started with Python Django (1)
Web application development with Flask
Getting Started with Python Django (4)
Getting Started with Python Django (3)
Getting Started with Python Django (6)
Getting Started with Django with PyCharm
Web application with Python + Flask ② ③
Python3 | Getting Started with numpy
Getting Started with Python Django (5)
Web application with Python + Flask ④
Getting Started with Flask # 2: Displaying Data Frames in Style Sheets
Getting Started with Python responder v2
Getting Started with Git (1) History Storage
Getting started with Sphinx. Generate docstring with Sphinx
Monitor Python web apps with Prometheus
Getting Started with Python for PHPer-Classes
Getting Started with Sparse Matrix with scipy.sparse
Getting Started with Julia for Pythonista
Getting Started with Python Basics of Python
Getting Started with Cisco Spark REST-API
Getting started with USD on Windows
Getting Started with Python Genetic Algorithms
Getting started with Python 3.8 on Windows
Getting Started with Python for PHPer-Functions
Getting Started with CPU Steal Time
[FastAPI] Getting started with FastAPI, an ASGI web framework made by Python
Efficiently develop Azure Python apps with CI/CD
Azure table storage with PTVS Flask app
Getting Started with python3 # 1 Learn Basic Knowledge
Create a simple web app with flask
Getting Started with Python for PHPer-Super Basics
Getting started with Dynamo from Python boto
Easy web app with Python + Flask + Heroku
Getting Started with Lisp for Pythonista: Supplement