[PYTHON] SNS Flask (Ajax) made with Flask

TL;DL

Udemy attendance record for the following courses

Web application development course with Python + Flask! !! ~ Master Flask from 0 to create SNS ~ https://www.udemy.com/course/flaskpythonweb/

This article describes asynchronous communication with Ajax.

What is Ajax

-Ajax (Asynchronous JavaScript and XML) is a complex technology such as HTML, CSS, and Javascript. It allows web applications to display pages faster and to partially update the interface without reloading the entire page. → Use when you want to update the page content without screen transition.


Official
https://flask.palletsprojects.com/en/1.1.x/patterns/jquery/

-Use google's CDN to use jQuery. Ajax API https://developers.google.com/speed/libraries

3.x snippet:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Code sample

Constitution sample ├── app.py └── templates    └── index.html

app.py

from flask import Flask, request, render_template, jsonify

app = Flask(__name__)

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

@app.route('/_add_numbers')
def add_numbers():

    # request.args.get(Query parameters,[Default value]、[Value type])
    a = request.args.get('a', 0, type=int)
    b = request.args.get('b', 0, type=int)

    # jsonify({key:value}):Convert the dictionary format data given as an argument to Json.
    #At that time, the header"content-type"To'application/json'Will convert to.
    return jsonify({'result': a+b})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(function(){
        $('a#calculate').bind('click', function(){
            $.getJSON('/_add_numbers', {
                a: $('input[name="a"]').val(),
                b: $('input[name="b"]').val()
            }, function(data){
                $("#result").text(data.result)
            });
        });
    });

</script>
<h1>Jquery Sample</h1>
<p>
    <input type="text" size=5 name='a'>+
    <input type="text" size=5 name='b'>=
    <span id='result'>?</span>
</p>
<a href="#" id='calculate'>Calculate</a>

Process flow

    1. Execute the process of the root directory of app.py and display index.html on the screen.
    1. When the "calculate" link is pressed, geJSON processing is executed in response to the click event. Get the input value from the fields a and b by getJSON process and execute the process of "/ _add_numbers" root defined in "app.py". (= Event processing)
    1. In add_numbers processing, the values ​​of a and b are acquired from the query parameters by request, and the result is returned to index.html in JSON format using the jsonify module.
  1. Pass the result of event processing to the event handler which is the third argument of getJSON (). (Data of "function (data)")
  2. Reflect the result received from add_numbers in the text of the tag with id = result.

screen image スクリーンショット 2021-01-17 14.07.27.png

スクリーンショット 2021-01-17 14.07.41.png

JQuery methods

reference: http://semooh.jp/jquery/

$('HTML element').bind( eventType [, eventData], handler(eventObject) ) 
Contents Explanation
.bind() Associate the subsequent processing with the HTML element
eventType A DOM event that is the key to invoking the process. You can specify multiple items separated by commas.'click''submit'Such
eventData Any. Data to be passed to eventHandler can be defined. (Function OK)
handler(eventObject) Define the process to be executed when an event with a low proposal occurs in eventType. If eventData is defined, it can be received as an argument of handler.(The name used for the argument is arbitrary)
$.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
Contents Explanation
url Specify the request destination URL.
data Specify the data to send to the server. URL-encoded before sending to the server.
callback A callback function that will be executed if the request is sent successfully. The value returned from the request destination URL can be received as an argument of the function.

Recommended Posts

SNS Flask (Ajax) made with Flask
SNS Python basics made with Flask
SNS made with Flask Flask (Blueprint, bcrypt)
SNS made with Flask Flask (login process by flask_login)
Send msgpack with ajax to flask (werkzeug) environment
I made a Mattermost bot with Python (+ Flask)
Container-like # 1 made with C
Container-like # 2 made with C
IP restrictions with Flask
Hello world with flask
Programming with Python Flask
Full-scale server made with Nginx + uWSGI + Flask + Ubuntu (installation)
Full-scale server made with Nginx + uWSGI + Flask + Ubuntu (implementation)
Simulate temperature measurement with Raspberry Pi + Flask + SQLite + Ajax
Twitter posting client made with Flask with simple login function
How to deploy a web app made with Flask to Heroku
Pomodoro timer made with Errbot
Touch Flask + run with Heroku
Hello World with Flask + Hamlish
Unit test flask with pytest
API with Flask + uWSGI + Nginx
I made blackjack with python!
Web application development with Flask
I made LINE-bot with Python + Flask + ngrok + LINE Messaging API
I made a simple book application with python + Flask ~ Introduction ~
(Failure) Deploy a web app made with Flask on heroku
View flask coverage with pytest-cov
Web application with Python + Flask ② ③
I made COVID19_simulator with JupyterLab
I made Word2Vec with Pytorch
File upload with Flask + jQuery
I made blackjack with Python.
Othello made with python (GUI-like)
I made wordcloud with Python.
Web application with Python + Flask ④
Until API made with Flask + MySQL is converted to Docker
I made a Nyanko tweet form with Python, Flask and Heroku
[LINE login] Verify state with Flask
[Memo] Links for developing with Flask
Creating a Flask server with Docker
Run the app with Flask + Heroku
Persist Flask API server with forever
[Python] Use Basic/Digest authentication with Flask
Numer0n with items made in Python
I made a fortune with Python.
Twitter posting application made with Django
Basic authentication and Digest authentication with Flask
Creating a simple app with flask
Build Flask environment with Dockerfile + docker-compose.yml
Othello game development made with Python
Commands for creating SNS with Django
Twitter search client made with bottle
I made a daemon with Python
Post bulletin board creation with flask
Application development with Docker + Python + Flask
Image upload function with Vue.js + Flask