欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

flask框架配置mysql數(shù)據(jù)庫(kù)操作詳解

 更新時(shí)間:2019年11月29日 11:37:31   作者:LuckyQueen0928  
這篇文章主要介紹了flask框架配置mysql數(shù)據(jù)庫(kù)操作,結(jié)合實(shí)例形式詳細(xì)分析了flask框架配置mysql數(shù)據(jù)庫(kù)及連接訪問(wèn)等相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了flask框架配置mysql數(shù)據(jù)庫(kù)操作。分享給大家供大家參考,具體如下:

該篇博客配置環(huán)境為:python版本3.5,flask2.0,python3中已經(jīng)不再支持MySQLdb模塊,所有這里我用了pymysql,所有使用前應(yīng)該

安裝pymysql:

pip install pymysql

在網(wǎng)上的好多資料都給的是使用sqlite的例子,由于很不喜歡所以今天分享一下flask-sqlalchemy操作mysql的方法.

以前習(xí)慣使用sqlalchemy,后來(lái)發(fā)現(xiàn)使用flask-sqlchemy還是要簡(jiǎn)單一些(起碼省去了好多模塊和類的導(dǎo)入,create_engine,sessionmaker,declarative。。。)不過(guò)flask官方的例子用的是sqlchemy,去官網(wǎng), flask-sqlalchemy官方文檔

這里寫一個(gè)簡(jiǎn)單的flask web程序,來(lái)說(shuō)明flask-sqlalchemy如何驅(qū)動(dòng)msyql數(shù)據(jù)庫(kù).為了偷懶,這個(gè)例子以上一篇博文flask藍(lán)圖的使用為基礎(chǔ).

首先看一下程序結(jié)構(gòu):

相比上一節(jié)只多了兩個(gè)文件,create_db.py,models.py

1.建立mysql和app的連接

在config.py中加入以下兩項(xiàng)配置:

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:xxxxx@localhost:3306/test?charset=utf8'
SQLALCHEMY_TRACK_MODIFICATIONS = True

如此在app/__init__.py中加入

app.config.from_object('config')
db = SQLAlchemy(app)

就可以完成app和數(shù)據(jù)的關(guān)聯(lián),并生成一個(gè)可以操作app數(shù)據(jù)庫(kù)的SQLAlchemy實(shí)例db

完整的app/__init__.py代碼如下:

from flask import Flask, url_for, request, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import models,views

2.創(chuàng)建app/models.py模塊

上代碼

from app import db #db是在app/__init__.py生成的關(guān)聯(lián)后的SQLAlchemy實(shí)例

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

3.創(chuàng)建create_db.py,表結(jié)構(gòu)設(shè)計(jì)完成后執(zhí)行python create_db.py即可完成表的創(chuàng)建,如下圖

#app/create_db.py

from app import db
db.create_all()

4.表已經(jīng)創(chuàng)建完成了,接下來(lái)是我們的業(yè)務(wù)邏輯使用表的時(shí)候了

分別在user和admin藍(lán)圖中增加一個(gè)add用戶的業(yè)務(wù)

#app/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)
  if not p_user or not p_email or not p_password:
   return 'input error'
  newobj = User(username=p_user, email=p_email, password=p_password)
  db.session.add(newobj)
  db.session.commit()
  users = User.query.all()
  return render_template('user/add.html',users=users)
 users = User.query.all()
 return render_template('user/add.html',users=users)
@user.route('/show')
def show():
 return 'user_show'

#app/admin.py

#admin.py
from flask import Blueprint,render_template, request, redirect
from app import db
from .models import Admin
admin = Blueprint('admin',__name__)
@admin.route('/index')
def index():
 return render_template('admin/index.html')
@admin.route('/add/',methods=['POST','GET'])
def add():
 if request.method == 'POST':
  p_admin = request.form.get('username',None)
  p_email = request.form.get('email',None)
  p_password = request.form.get('password',None)
  if not p_admin or not p_email or not p_password:
   return 'input error'
  newobj = Admin(username=p_admin, email=p_email, password=p_password)
  db.session.add(newobj)
  db.session.commit()
  admins = Admin.query.all()
  return render_template('admin/add.html',admins=admins)
 admins = Admin.query.all()
 return render_template('admin/add.html',admins=admins)
@admin.route('/show')
def show():
 return 'admin_show'

#app/templates/admin/add.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>AdminsAdd</title>
</head>
<body>
<form action="/admin/add/" method="POST">
 user:<input type="text" name="username" />
 email:<input type="text" name="email" />
 pwd:<input type="password" name="password" />
 <input type="submit" value="add" />
</form>
{% if admins %}
<table border="1px">
 <tr>
  <th>UserName</th>
  <th>Email</th>
 </tr>
 {% for u in admins %}
  <tr>
   <td>{{u.username}}</td>
   <td>{{u.email}}</td>
  </tr>
 {% endfor %}
</table>
{% endif %}
</body>
</html>

#app/templates/user/add.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>UserAdd</title>
</head>
<body>
<form action="/user/add/" method="POST">
 user:<input type="text" name="username" />
 email:<input type="text" name="email" />
 pwd:<input type="password" name="password" />
 <input type="submit" value="add" />
</form>
{% if users %}
<table border="1px">
 <tr>
  <th>UserName</th>
  <th>Email</th>
 </tr>
 {% for u in users %}
  <tr>
   <td>{{u.username}}</td>
   <td>{{u.email}}</td>
  </tr>
 {% endfor %}
</table>
{% endif %}
</body>
</html>

#app/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')

#run.py

from app import app
app.run()

到這里也就結(jié)束了,這樣這個(gè)例子就結(jié)合了藍(lán)圖和flask-sqlalchemy.本例中只使用了db.session.add(),其它的還有db.session.delete()...

看一下效果:

localhost:5000/user/add

localhost:5000/admin/add

希望本文所述對(duì)大家基于flask框架的Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • Python最基本的數(shù)據(jù)類型以及對(duì)元組的介紹

    Python最基本的數(shù)據(jù)類型以及對(duì)元組的介紹

    這篇文章主要介紹了Python最基本的數(shù)據(jù)類型以及對(duì)元組的介紹,來(lái)自于IBM官方網(wǎng)站技術(shù)文檔,需要的朋友可以參考下
    2015-04-04
  • django利用request id便于定位及給日志加上request_id

    django利用request id便于定位及給日志加上request_id

    這篇文章主要介紹了django利用request id便于定位及給日志加上request_id的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用django具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧
    2018-08-08
  • Python如何存儲(chǔ)數(shù)據(jù)到j(luò)son文件

    Python如何存儲(chǔ)數(shù)據(jù)到j(luò)son文件

    這篇文章主要介紹了Python如何存儲(chǔ)數(shù)據(jù)到j(luò)son文件,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-03-03
  • Python有序容器的 sort 方法詳解

    Python有序容器的 sort 方法詳解

    這篇文章主要介紹了Python有序容器的 sort 方法,容器.sort(key=選擇排序依據(jù)的函數(shù), reverse=True|False) 可以將有序容器進(jìn)行排序,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-09-09
  • Python3編碼問(wèn)題 Unicode utf-8 bytes互轉(zhuǎn)方法

    Python3編碼問(wèn)題 Unicode utf-8 bytes互轉(zhuǎn)方法

    今天小編就為大家分享一篇Python3編碼問(wèn)題 Unicode utf-8 bytes互轉(zhuǎn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-10-10
  • Python 多維List創(chuàng)建的問(wèn)題小結(jié)

    Python 多維List創(chuàng)建的問(wèn)題小結(jié)

    這篇文章主要介紹了Python 多維List創(chuàng)建的問(wèn)題小結(jié),詳細(xì)的介紹了遇到的一個(gè)小問(wèn)題的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • scipy稀疏數(shù)組coo_array的實(shí)現(xiàn)

    scipy稀疏數(shù)組coo_array的實(shí)現(xiàn)

    本文主要介紹了scipy稀疏數(shù)組coo_array的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-02-02
  • Pycharm遠(yuǎn)程調(diào)試原理及具體配置詳解

    Pycharm遠(yuǎn)程調(diào)試原理及具體配置詳解

    這篇文章主要介紹了Pycharm遠(yuǎn)程調(diào)試原理及具體配置詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • python 刪除excel表格重復(fù)行,數(shù)據(jù)預(yù)處理操作

    python 刪除excel表格重復(fù)行,數(shù)據(jù)預(yù)處理操作

    這篇文章主要介紹了python 刪除excel表格重復(fù)行,數(shù)據(jù)預(yù)處理操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-07-07
  • Python網(wǎng)絡(luò)爬蟲(chóng)的基本原理解析

    Python網(wǎng)絡(luò)爬蟲(chóng)的基本原理解析

    如果要獲取網(wǎng)絡(luò)上數(shù)據(jù),我們要給爬蟲(chóng)一個(gè)網(wǎng)址(程序中通常叫URL),爬蟲(chóng)發(fā)送一個(gè)HTTP請(qǐng)求給目標(biāo)網(wǎng)頁(yè)的服務(wù)器,服務(wù)器返回?cái)?shù)據(jù)給客戶端(也就是我們的爬蟲(chóng)),爬蟲(chóng)再進(jìn)行數(shù)據(jù)解析、保存等一系列操作,需要的朋友可以參考下
    2023-05-05

最新評(píng)論