การใช้ flask_sqlalchemy สร้างตาราง ฐานข้อมูล ในภาษา python

แชร์ความรู้ภาษา Python ไพทอน การเขียนโปรแกรมภาษาไพทอน

Moderator: mindphp, ผู้ดูแลกระดาน

ภาพประจำตัวสมาชิก
jirawoot
PHP VIP Members
PHP VIP Members
โพสต์: 3129
ลงทะเบียนเมื่อ: 17/06/2019 10:30 am

การใช้ flask_sqlalchemy สร้างตาราง ฐานข้อมูล ในภาษา python

โพสต์ที่ยังไม่ได้อ่าน โดย jirawoot »

การใช้ flask_sqlalchemy สร้างตาราง ฐานข้อมูล ในภาษา python
คนที่กำลังวิธีการสร้างฐานข้อมูล ผมมีวิธีมาแชร์ครับ เป็นไลบารี่ของภาษา Python ที่ใช้สำหรับการเชื่อมต่อสำหรับฐานข้อมูลเพื่อจะใช้ในการสร้างตาราง โดยจะต้องติดตั้ง postgresql ลงเครื่องก่อน และทำการติดตั้ง flask_sqlalchemy ด้วย แล้วทำการเรียกใช้ module flask_sqlalchemy ประโยชน์ของ module ตัวนี้คือ สามารถเขียนโดยใช้ภาษา python เพื่อในสร้างตาราง ได้เลย ส่วนของการติดตั้งนะครับ
ใช้คำสั่ง

โค้ด: เลือกทั้งหมด

pip install SQLAlchemy
คำสั่งในการสร้างตารางนะครับ

โค้ด: เลือกทั้งหมด

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app =Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:@localhost/test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class usertest(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    fristname = db.Column(db.String(100),nullable=False,unique=False)
    lastname = db.Column(db.String(100), nullable=False, unique=False)
    username = db.Column(db.String(100),unique=True,nullable=False)
    password = db.Column(db.String(100),primary_key=False, unique=False,nullable=False)
    level = db.Column(db.Integer, primary_key=False, unique=False, nullable=False)
    def __init__(self, fristname, lastname, username,password,level):
        self.fristname=fristname
        self.lastname = lastname
        self.username=username
        self.password=password
        self.level = level
if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)
จากโค้ดนะครับผมจะสร้างตารางชื่อว่า usertest โดยจะมี colum คือ id,fristname, lastname, username,password, level และฐานข้อมูลมีชื่อว่า test
Selection_088.png
Selection_088.png (23.44 KiB) Viewed 1637 times
จากรูปนะครับในฐานข้อมูล test ยังไม่มีตาราง usertest นะครับเราก็ทำการรันโปรแกรมก็จะได้ตาราง usertest มาดังรูป
ผลลัพธ์
Selection_089.png
Selection_089.png (23.1 KiB) Viewed 1637 times
Selection_090.png
Selection_090.png (16.2 KiB) Viewed 1637 times


อ้างอิง
https://www.scotch.io/tutorials/authentication-and-authorization-with-flask-login
https://www.realpython.com/using-flask-login-for-user-management-with-flask/
https://www.blog.openshift.com/use-flask-login-to-add-user-authentication-to-your-python-application/
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 99