flask——flask-sqlachemy的使用,模塊劃分

假設有兩個類別的模塊:admin和user模塊html

1、flask-sqlachemy的使用

一、使用創建mysql的鏈接

新建一個目錄:app,如下操做所有在app目錄下python

a)新建config.py文件,寫入如下內容mysql

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:xxxxx@localhost:3306/test?charset=utf8'  # 使用pymysql創建鏈接
SQLALCHEMY_TRACK_MODIFICATIONS = True  

b)在app/__init__.py中寫入sql

from flask import Flask, url_for, request, redirect, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')	# 完成app與配置文件的關聯
db = SQLAlchemy(app)	# 生成一個能夠操做app數據庫的SQLAlchemy實例db

from app import models,views

二、建立model.py模塊

from app import db 		# db是在app/__init__.py生成的關聯後的SQLAlchemy實例

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(320), unique=True)
    password = db.Column(db.String(32), nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username


class Admin(db.Model):
    __tablename__ = 'admins'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(320), unique=True)
    password = db.Column(db.String(32), nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username

三、建立create_db.py

from app import db
db.create_all()

表結構設計完成後執行python create_db.py便可完成表的建立數據庫

2、視圖函數

一、user.py

from flask import Blueprint, render_template, redirect,request
from app import db
from .models import User

user = Blueprint('user',__name__)	 # 初始化當前視圖函數的

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

@user.route('/add/',methods=['GET','POST'])		# 方式
def add():
    if request.method == 'POST':	
        p_user = request.form.get('username',None)		# 獲取表單提交的值
        p_email = request.form.get('email',None)
        p_password = request.form.get('password',None)
		
		# 增
        obj = User(username=p_user, email=p_email, password=p_password)
		db.session.add(obj)
        db.session.commit()		# 提交操做
		
		# 刪
		obj = User(username=p_user, email=p_email, password=p_password)
		db.session.delete(obj)
        db.session.commit()		# 提交操做
        
		# 查(此種方法,不存在返回None)
		result = User.query.filter_by(username=p_user).first()
		result_list = User.query.all()
		
		# 改
		User.query.filter_by(username=p_user).update({'username':'abc123'})
		
        return render_template('user/add.html',users=users)
	else:
		users = User.query.all()
		return render_template('user/add.html',users=users)

二、admin.py

from flask import Blueprint

admin = Blueprint('admin',__name__)

@admin.route('/index')
def index():
    return "hello,world!"

三、views.py

from app import app
from .admin import admin
from .user import user

app.register_blueprint(admin,url_prefix='/admin')
app.register_blueprint(user, url_prefix='/user')

3、運行

run.py

from app import app
app.run()

參考於:這裏flask

相關文章
相關標籤/搜索