pip install pymysql
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
from flask import Flask,render_template,request,make_response,session from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.secret_key = 'fff' #app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/db_name' app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:@localhost/test' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username #admin = User('admin', 'admin@example.com') #db.create_all() # In case user table doesn't exists already. Else remove it. #db.session.add(admin) #db.session.commit() # This is needed to write the changes to database #User.query.all() #User.query.filter_by(username='admin').first() @app.route('/') def index(): #initialize db.create_all() #create admin = User('admin', 'admin@example.com') db.session.add(admin) db.session.commit() #read user=User.query.filter_by(username='admin').first() #update user.email='akash073@gmail.com' db.session.commit() #delete db.session.delete(user) db.session.commit() |