[PYTHON] ballon

flask.py


import _sqlite3

from flask import Flask
from flask import g
from flask import render_template
from flask import request
from flask import Response

app = Flask(__name__)


def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = _sqlite3.connect('test_sqlite.db')
    return db


@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()


@app.route('/employee', methods=['POST', 'PUT', 'DELETE'])
@app.route('/employee/<name>', methods=['GET'])
def employee(name=None):
    db = get_db()
    curs = db.cursor()
    curs.execute(
        'CREATE TABLE if NOT EXISTS persons('
        'id INTEGER PRIMARY KEY AUTOINCREMENT, name STRING)'
    )
    db.commit()

    name = request.values.get('name',name)
    if request.method == 'GET':
        curs.execute('SELECT * FROM persons WHERE name ="{}"'.format(name))
        person = curs.fetchone()
        if not person:
            return "NO", 404
        user_id, name = person
        return '{}:{}'.format(user_id,name), 200

    if request.method == 'POST':
        curs.execute('INSERT INTO persons(name) values("{}")'.format(name))
        db.commit()
        return 'created {}'.format(name), 201

    if request.method == 'PUT':
        new_name = request.values['new_name']
        curs.execute('UPDATE persons set name = "{}" WHERE name = "{}"'.format(new_name, name))
        db.commit()
        return 'updated {}: {}'.format(name, new_name), 200

    if request.method == 'DELETE':
        curs.execute('DELETE from persons WHERE name = "{}"'.format(name))
        db.commit()
        return 'deleted {}'.format(name), 200

    curs.close()

@app.route('/')
def hello_word():
    return 'top'


@app.route('/hello')
@app.route('/hello/<username>')
def hello_word2(username=None):
    #return 'hello world! {}'.format(username)
    return render_template('hello.html', username=username)


@app.route('/post', methods=['POST', 'PUT', 'DELETE'])
def show_post():
    return str(request.values)


def main():
    app.debug = True
    app.run()
    #app.run(host='127.0.0.1', port=5000)


if __name__ == '__main__':
    main()

test_flask.py


import requests

r = requests.get('http://127.0.0.1:5000/employee', data={'username': 'jun'})
print(r.text)

r = requests.post('http://127.0.0.1:5000/employee', data={'username': 'jun'})
print(r.text)

r = requests.put('http://127.0.0.1:5000/employee', data={
    'username': 'jun', 'new_name': 'sakai'})
print(r.text)

r = requests.delete('http://127.0.0.1:5000/employee', data={'username': 'jun'})
print(r.text)

hello.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>

{% if username %}
Hello {{ username }}
{% else %}
Hello
{% endif %}

</body>
</html>

Recommended Posts

ballon
ballon
Premier flacon
Mémo du flacon
Paramètres initiaux du flacon
À propos de la personnalisation de Flask
Introduction au développement de flacons
J'ai touché Flask
Introduction à Flask (Windows)
Mémo Primer Flask
Notes sur Flask
Mémo de base Flask
Paramètres de l'application Flask
Depuis le proxy Redis de Flask
Paramètres de la base de données Flask
Certification Flask Basic
Présentation de WebPay de Flask
Flacon facile à utiliser
Tutoriel Flask # 3 ~ DB Linkage ~
Restriction IP avec Flask
Supprimer la journalisation des flacons python3
Page de résumé de l'article Flask
Personnaliser les journaux d'accès Flask
Mémorandum de construction du site Flask
Bonjour le monde sur flacon
Paramètres du modèle HTML Flask
Exécutez Apache2 + WSGI + Flask
Programmation avec Python Flask
Téléchargeur d'images avec Flask
support de squelette de fiole de gae
Introduction de flacon - Mémo d'application Blueprint