Python Web framework Flask: website development entry instance, pythonflask

Source: Internet
Author: User

Python Web framework Flask: website development entry instance, pythonflask

1. Introduction to Flask

Flask is a Web development microframework implemented by Python. Official Website: http://flask.pocoo.org/

Ii. Demo

1. code structure

Copy codeThe Code is as follows:
.
── Blog. py
── Static
│ ── Css
│ ── Index.css
│ ── Images
│ ── Cat.jpg
│ └ ── Sheying1229.jpg
│ ── Js
└ ── Templates
── Index.html
── Login.html
── Regist.html
── Upload.html

5 directories, 8 files

2. Main Program blog. py
Copy codeThe Code is as follows:
#! /Usr/bin/python
# Coding: utf8

From flask import Flask, render_template, url_for, request, redirect, make_response, session
Import OS, MySQLdb

App = Flask (_ name __)
App. secret_key = 'afjlsjfowflajflkajfkjfkaljf'
User_list = ['Jim ', 'max', 'py']

Imagepath = OS. path. join (OS. getcwd (), "static/images ")

@ App. route ('/')
Def index ():
Username = request. cookies. get ('username ')
If not username:
Username = U' log on First'
Islogin = session. get ('islogin ')
Nav_list = [u 'homepage ', u 'economical', u 'cultural ', u 'tech', u 'entertaining ']
Blog = {'title': 'Welcome to my blog ', 'content': 'Hello, welcome to my blog .'}
Blogtag = {'javascript ': 10, "python": 20, "shell": 5}
Img = url_for ('static ', filename = "images/cat.jpg ")
Return render_template('index.html ', nav_list = nav_list, username = username, blog = blog, blogtag = blogtag, img = img, islogin = islogin)

@ App. route ('/reg', methods = ['get', 'post'])
Def regist ():
If request. method = 'post ':
Username = request. form ['username']
Conn = MySQLdb. connect (user = 'root', passwd = 'admin', host = '2017. 0.0.1 ')
Conn. select_db ('blog ')
Curr = conn. cursor ()
SQL = 'insert into 'user' ('id', 'username') values (% d, "% s") '% (1, username)
Curr.exe cute (SQL)
Conn. commit ()
Curr. close ()
Conn. close ()
Return "user % s regist OK! "% Request. form ['username']
Else:
# Request. args ['username']
Return render_template('regist.html ')

@ App. route ('/upload', methods = ['get', 'post'])
Def upload ():
If request. method = 'post ':
Username = request. form ['username']
File = request. files ['img ']
Filename = file. filename
File. save (OS. path. join (imagepath, filename ))
Return " "% filename
Else:
Return render_template('upload.html ')

@ App. route ('/login/', methods = ['get', 'post'])
Def login ():
If request. method = 'post ':
Username = request. form. get ('username ')
If username in user_list:
Response = make_response (redirect ('/'))
Response. set_cookie ('username', value = username, max_age = 300)
Session ['islogin'] = '1'
Return response
Else:
Session ['islogin'] = '0'
Return redirect ('/login /')
Else:
Return render_template('login.html ')

If _ name _ = '_ main __':
App. run (debug = True, host = '0. 0.0.0 ', port = 5000)

It mainly includes the homepage, registration, logon, and upload pages.

Blog. py shows common functions and usage of Flask: routing, database operations, cookie, session, redirect, form, file upload, debugging, IP address and port of the Web server, static File Reading.

3rd, the first page template index.html
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8"/>
<Title> Flask DEMO </title>
<Link rel = "stylesheet" type = "text/css" href = "static/css/index.css"/>
</Head>
<Body>
<Div class = "header">
{% If islogin = '1' %}
<H1> Welcome, {username }}! </H1>
{% Else %}
<H1 >{{ username }}! </H1>
{% Endif %}
<Div class = "nav">
<Ul>
{% For nav in nav_list %}
<Li> <a href = "{nav}" >{{ nav }}</a> </li>
{% Endfor %}
</Ul>
</Div>
</Div>
<Div class = "container">
<Div class = "item">
<H1 >{{ blog ['title'] }}<Div class = "content">

<P >{{ blog ['content'] }}</p>

</Div>
</Div>
<Div class = "side">
<Ul>
{% For key, value in blogtag. items () %}
<Li >{{ key }}( {value }}) </li>
{% Endfor %}
</Ul>
</Div>
</Div>
</Body>
</Html>

This template mainly shows how to read various types of variables in the Flask template.

Login.html

Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8"/>
<Title> Login </title>
<Link rel = "stylesheet" type = "text/css" href = "static/css/index.css"/>
</Head>
<Body>
<Div class = "header">
<H1> Login </Div>
<Div class = "container">
<Div class = "item">
<Form action = "" method = "post">
<Input type = "text" placeholder = "please input username" name = "username"/> <br/>
<Input type = "submit" value = "Login"/>
</Form>
</Div>
</Div>
</Body>
</Html>

The combination of blog. py mainly shows how the form submits values, cookie and session applications.

5 forbidden registration page regist.html

Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8"/>
<Title> Regist </title>
<Link rel = "stylesheet" type = "text/css" href = "static/css/index.css"/>
</Head>
<Body>
<Div class = "header">
<H1> Regist </Div>
<Div class = "container">
<Div class = "item">
<Form action = "" method = "post">
<Input type = "text" placeholder = "please input username" name = "username"/> <br/>
<Input type = "submit" value = "Regist"/>
</Form>
</Div>
</Div>
</Body>
</Html>

Combined with blog. py, it mainly shows database operations.

6、upload page upload.html
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8"/>
<Title> Upload </title>
<Link rel = "stylesheet" type = "text/css" href = "static/css/index.css"/>
</Head>
<Body>
<Div class = "header">
<H1> Upload </Div>
<Div class = "container">
<Div class = "item">
<Form action = "" method = "post" enctype = "multipart/form-data">
<Input type = "text" name = "username"/> <br/>
<Input type = "file" name = "img"/> <br/>
<Input type = "submit" value = "Upload"/>
</Form>
</Div>
</Div>
</Body>
</Html>

The combination of blog. py mainly shows how to upload files.

7. Running Effect

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.