6626070
2997924

PL00, WEB

Back to the previous pagepage management
List of posts to read before reading this article


Contents


OSI layers : Open Systems Interconnection Reference Model

OSI


Jekyll, github

step 1, repository : [user_name].github.io

image





step 2, jekyllthemes

image





step 3, _config.yml

url     : "https://[your_name].github.io"
baseurl : ""

image





step 4, aceess

access url : https://[your_name].github.io

image





Flask

main URL
sqlalchemy URL




Installation

$ pip install Flask
$ pip install flask-sqlalchemy
$ pip install Flask-WTF
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run()





sqlalchemy : create db.sqlite!

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

basedir = os.path.abspath(os.path.dirname(__file__))
dbfile = os.path.join(basedir, 'db.sqlite')

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + dbfile
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Test(db.Model):
    __tablename__ = 'test_table'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32), unique=True)

db.create_all()





Jinja2

URL
Jinja is a web template engine for the Python programming language and is licensed under a BSD License created by Armin Ronacher.




render_template

image templates/template.html

<html>
    
    <head>
    </head>
    
    <body>
        <p>Hello, World!</p>
    </body>
    
</html>

app.py

from flask import Flask
from flask import render_template

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run()





**

import os
from flask import Flask
from flask import request
from flask import redirect
from flask import render_template
from models import db

from models import Fcuser

app = Flask(__name__)

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        userid = request.form.get('userid')
        username = request.form.get('username')
        password = request.form.get('password')
        re_password = request.form.get('re-password')

        if (userid and username and password and re_password) and password == re_password:
            fcuser = Fcuser()
            fcuser.userid = userid
            fcuser.username = username
            fcuser.password = password

            db.session.add(fcuser)
            db.session.commit()

            return redirect('/')

    return render_template('register.html')

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

if __name__ == "__main__":
    basedir = os.path.abspath(os.path.dirname(__file__))
    dbfile = os.path.join(basedir, 'db.sqlite')

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + dbfile
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db.init_app(app)
    db.app = app
    db.create_all()
    app.run(host='127.0.0.1', port=5000, debug=True)





Several functions

sign up

M : model
image

$ mkdir templates; cd templates
$ touch index.html

templates/index.html

<html>
    <head>
    </head>
    <body>
        <p>Hello, World!</p>
    </body>
</html>

app.py

import os
from flask import Flask
from flask import render_template
from models import db

app = Flask(__name__)

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

if __name__ == "__main__":
    basedir = os.path.abspath(os.path.dirname(__file__))
    dbfile = os.path.join(basedir, 'db.sqlite')

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + dbfile
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db.init_app(app)
    db.app = app
    db.create_all()
    app.run(host='127.0.0.1', port=5000, debug=True)

models.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Fcuser(db.Model):
    __tablename__ = 'fcuser'
    id = db.Column(db.Integer, primary_key=True)
    password = db.Column(db.String(64))
    userid = db.Column(db.String(32))
    username = db.Column(db.String(8))




V : view (with bootstrap)
bootstrap URLbootstrap4 tutorials
image

templates/index.html

<html>
    
    <head>
    </head>
    
    <body>
        <p>Hello, World!</p>
    </body>
    
</html>

templates/register.html

<html>

<head>
  <meta charset='utf-8' />
  <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no' />

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
  </script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
  </script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
  </script>
</head>

<body>
  <div class="container">
    <div class="row mt-5">
      <h1>Sign up</h1>
    </div>
    <div class="row mt-5">
      <div class="col-12">
        <form method="POST">
          <div class="form-group">
            <label for="userid">USER ID</label>
            <input type="text" class="form-control" id="userid" placeholder="user id" name="userid" />
          </div>
          <div class="form-group">
            <label for="username">USER NAME</label>
            <input type="text" class="form-control" id="username" placeholder="user name" name="username" />
          </div>
          <div class="form-group">
            <label for="password">PASSWORD</label>
            <input type="password" class="form-control" id="password" placeholder="password" name="password" />
          </div>
          <div class="form-group">
            <label for="re-password">RE-PASSWORD</label>
            <input type="password" class="form-control" id="re-password" placeholder="re-password" name="re-password" />
          </div>
          <button type="submit" class="btn btn-primary">SUBMIT</button>
        </form>
      </div>
    </div>
  </div>
</body>

</html>

app.py

import os
from flask import Flask
from flask import render_template
from models import db

app = Flask(__name__)

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

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

if __name__ == "__main__":
    basedir = os.path.abspath(os.path.dirname(__file__))
    dbfile = os.path.join(basedir, 'db.sqlite')

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + dbfile
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db.init_app(app)
    db.app = app
    db.create_all()
    app.run(host='127.0.0.1', port=5000, debug=True)

models.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Fcuser(db.Model):
    __tablename__ = 'fcuser'
    id = db.Column(db.Integer, primary_key=True)
    password = db.Column(db.String(64))
    userid = db.Column(db.String(32))
    username = db.Column(db.String(8))




C : controller
image

templates/index.html

<html>
    
    <head>
    </head>
    
    <body>
        <p>Hello, World!</p>
    </body>
    
</html>

templates/register.html

<html>

<head>
  <meta charset='utf-8' />
  <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no' />

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
  </script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
  </script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
  </script>
</head>

<body>
  <div class="container">
    <div class="row mt-5">
      <h1>Sign up</h1>
    </div>
    <div class="row mt-5">
      <div class="col-12">
        <form method="POST">
          <div class="form-group">
            <label for="userid">USER ID</label>
            <input type="text" class="form-control" id="userid" placeholder="user id" name="userid" />
          </div>
          <div class="form-group">
            <label for="username">USER NAME</label>
            <input type="text" class="form-control" id="username" placeholder="user name" name="username" />
          </div>
          <div class="form-group">
            <label for="password">PASSWORD</label>
            <input type="password" class="form-control" id="password" placeholder="password" name="password" />
          </div>
          <div class="form-group">
            <label for="re-password">RE-PASSWORD</label>
            <input type="password" class="form-control" id="re-password" placeholder="re-password" name="re-password" />
          </div>
          <button type="submit" class="btn btn-primary">SUBMIT</button>
        </form>
      </div>
    </div>
  </div>
</body>

</html>

app.py

import os
from flask import Flask
from flask import request
from flask import redirect
from flask import render_template
from models import db
from models import Fcuser

app = Flask(__name__)

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

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        userid = request.form.get('userid')
        username = request.form.get('username')
        password = request.form.get('password')
        re_password = request.form.get('re-password')

        if (userid and username and password and re_password) and password == re_password:
            fcuser = Fcuser()
            fcuser.userid = userid
            fcuser.username = username
            fcuser.password = password

            db.session.add(fcuser)
            db.session.commit()

            return redirect('/')

    return render_template('register.html')
    
if __name__ == "__main__":
    basedir = os.path.abspath(os.path.dirname(__file__))
    dbfile = os.path.join(basedir, 'db.sqlite')

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + dbfile
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db.init_app(app)
    db.app = app
    db.create_all()
    app.run(host='127.0.0.1', port=5000, debug=True)    

models.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Fcuser(db.Model):
    __tablename__ = 'fcuser'
    id = db.Column(db.Integer, primary_key=True)
    password = db.Column(db.String(64))
    userid = db.Column(db.String(32))
    username = db.Column(db.String(8))




Flask-WTF
Installation

$ pip install Flask-WTF




log in

Session(Cookies)
image





Static files





REST





JQuery JWT





Flask for Scientific Web Applications

URL
templates/graphs.html

<!DOCTYPE html>
<html>
<title>Graphs</title>
<body>
    <div>Graph1</div>
    <div><img src=''></img></div>
    <div>Graph2</div>
    <div><img src=''></img></div>
    <div>Graph3</div>
    <div><img src=''></img></div>
</body>
</html>

flask_app.py

from flask import Flask, render_template
from graph import build_graph
 
app = Flask(__name__)
 
@app.route('/graphs')
def graphs():
    #These coordinates could be stored in DB
    x1 = [0, 1, 2, 3, 4]
    y1 = [10, 30, 40, 5, 50]
    x2 = [0, 1, 2, 3, 4]
    y2 = [50, 30, 20, 10, 50]
    x3 = [0, 1, 2, 3, 4]
    y3 = [0, 30, 10, 5, 30]
 
    graph1_url = build_graph(x1,y1);
    graph2_url = build_graph(x2,y2);
    graph3_url = build_graph(x3,y3);
 
    return render_template('graphs.html',
    graph1=graph1_url,
    graph2=graph2_url,
    graph3=graph3_url)
 
if __name__ == '__main__':
    app.debug = True
    app.run()

graph.py

import matplotlib; matplotlib.use('TkAgg');import matplotlib.pyplot as plt
import io
import base64
 
def build_graph(x_coordinates, y_coordinates):
    img = io.BytesIO()
    plt.plot(x_coordinates, y_coordinates)
    plt.savefig(img, format='png')
    img.seek(0)
    graph_url = base64.b64encode(img.getvalue()).decode()
    plt.close()
    return 'data:image/png;base64,{}'.format(graph_url)





Distribution

Ubuntu : nginx + uwsgi

URL

$ apt-get update
$ apt-get install nginx
$ cd /etc/nginx/sites-available; sudo touch [file_name]

file_name

server {
    listen 80;
    server_name [ip_address_or_domain_name];

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/tmp/myflask.sock;
    }
}
$ sudo ln -s /etc/nginx/sites-available/myflask /etc/nginx/sites-enabled
$ sudo rm /etc/nginx/sites-enabled/default
$ sudo service nginx restart
$ conda config --add channels conda-forge
$ conda create -n [vir_env_name]
$ conda activate [vir_env_name]
$ conda install uwsgi
$ sudo apt install python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools
$ uwsgi --socket 0.0.0.0:5000 --protocol=http





Flask : Project





Django, basic

Django URL

Web framework

image





MVC(MTV)

  • M : Model
  • V : View
  • T : Templete

project and app
install django

$ pip install django

create project-folder

$ django-admin startproject [project_name]

create app-folder

$ django-ammin startapp [name_of_app]

run server

$ python manage.py runserver
examples

caution : create app-folder under project-folder

$ pip install django

$ django-admin startproject web_project
$ cd web_project
$ django-ammin startapp board
$ django-ammin startapp fcuser

$ mkdir board\templates
$ mkdir fcuser\templates

image

image

and then, modify contents of INSTALLED_APPS on settings.py in web_project as follows,

image





MVC(MTV), M(member)




MVC(MTV), database




MVC(MTV), admin




MVC(MTV), TV(sign up)





static file(with CDN)





log in

sign in




session

image




inheritance




form





Bulletin board





Distribution





Django, advanced





Django : Project 1





Django : Project 2





Django : Project 3





Tools

Chrome developer tools(F12)





List of posts followed by this article


Reference


OUTPUT