首页 > 编程 > Python > 正文

Python Web框架Flask下网站开发入门实例

2020-02-23 06:24:16
字体:
来源:转载
供稿:网友

一、Flask简介

Flask 是一个 Python 实现的 Web 开发微框架。官网:http://flask.pocoo.org/

二、Demo

1、代码结构

代码如下:
.
├── 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、主程序blog.py
代码如下:
#!/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'请先登录'
    islogin = session.get('islogin')
    nav_list = [u'首页',u'经济',u'文化',u'科技',u'娱乐']
    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='127.0.0.1')
        conn.select_db('blog')
        curr = conn.cursor()
        sql = 'insert into `user` (`id`,`username`) values (%d,"%s")' % (1,username)
        curr.execute(sql)
        conn.commit()
        curr.close()
        conn.close()
        return "user %s regist ok!" % request.form['username']
    else:
        #request.args['username']
        return render_template('regist.html')

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表