Upgrade to Pro — share decks privately, control downloads, hide ads and more …

glnagano-python peewee

glnagano-python peewee

hATrayflood

July 28, 2018
Tweet

More Decks by hATrayflood

Other Decks in Programming

Transcript

  1. 2018/7/28 ⻑野Python会 with NSEG from peewee import * db =

    SqliteDatabase("test.db") class User(Model): name = CharField() email = CharField() class Meta: database = db db.create_tables([User]) by ABE Hiroki aka hATrayflood
  2. 2018/7/28 ⻑野Python会 with NSEG CREATE TABLE "user" ("id" INTEGER NOT

    NULL PRIMARY KEY, "name" VARCHAR(255) NOT NULL, "email" VARCHAR(255) NOT NULL) idは⾃動で定義されるAUTOINCREMENT型 ※sqliteではintegerとprimary keyの 組み合わせでも機能する by ABE Hiroki aka hATrayflood
  3. 2018/7/28 ⻑野Python会 with NSEG user = User(name="hATrayflood", \ email="h.rayfl[email protected]") user.save()

    user = User.get(User.email==\ "h.rayfl[email protected]") user.name = "h.rayflood" user.save() by ABE Hiroki aka hATrayflood
  4. 2018/7/28 ⻑野Python会 with NSEG users = [] users.append({"name":"hATrayflood", \ "email":"h.rayfl[email protected]"})

    with db.manual_commit(): db.begin() try: User.insert_many(users).execute() db.commit() except: db.rollback() by ABE Hiroki aka hATrayflood
  5. 2018/7/28 ⻑野Python会 with NSEG だいたい使える docs.peewee-orm.com/en/latest/peewee /models.html#field-types-table null, unique, collationなども指定可能

    docs.peewee-orm.com/en/latest/peewee /models.html#field-initialization-arguments by ABE Hiroki aka hATrayflood
  6. 2018/7/28 ⻑野Python会 with NSEG & | == != < <=

    > >= << >> % ** ^ ~ by ABE Hiroki aka hATrayflood
  7. 2018/7/28 ⻑野Python会 with NSEG User.get(User.name%"%ray%") # WHERE name LIKE "%ray%"

    # mysql # WHERE name LIKE BINARY "%ray%" by ABE Hiroki aka hATrayflood
  8. 2018/7/28 ⻑野Python会 with NSEG User.get(User.name**"%ray%") # WHERE name ILIKE "%ray%"

    # mysql # WHERE name LIKE "%ray%" by ABE Hiroki aka hATrayflood
  9. 2018/7/28 ⻑野Python会 with NSEG User.select().where(~(User.name<<["hoge", "fuga"])) # WHERE NOT (name

    IN ("hoge", "fuga")) User.select().where(~(User.name>>None)) # WHERE NOT (name IS NULL) by ABE Hiroki aka hATrayflood
  10. 2018/7/28 ⻑野Python会 with NSEG class Post(Model): user = ForeignKeyField(User) text

    = TextField() posted_at = TimestampField() class Meta: database = db db.create_tables([Post]) by ABE Hiroki aka hATrayflood
  11. 2018/7/28 ⻑野Python会 with NSEG CREATE TABLE "post" ("id" INTEGER NOT

    NULL PRIMARY KEY, "user_id" INTEGER NOT NULL, "text" TEXT NOT NULL, "posted_at" INTEGER NOT NULL, FOREIGN KEY ("user_id") REFERENCES "user" ("id")) 外部キー制約まで⾃動⽣成する by ABE Hiroki aka hATrayflood
  12. 2018/7/28 ⻑野Python会 with NSEG post = Post(user=user, text="hoge hoge") post.posted_at

    = datetime.datetime.now() post.save() posts = Post.select().where(Post.user==\ user).order_by(Post.posted_at.desc()) posts.count() by ABE Hiroki aka hATrayflood
  13. 2018/7/28 ⻑野Python会 with NSEG class Tag(Model): label = TextField() class

    Meta: database = db class Post(Model): user = ForeignKeyField(User, backref="posts") text = TextField() posted_at = TimestampField() tags = ManyToManyField(Tag, backref="posts") class Meta: database = db db.create_tables([Tag, Post, \ Post.tags.get_through_model()]) by ABE Hiroki aka hATrayflood
  14. 2018/7/28 ⻑野Python会 with NSEG CREATE TABLE "post_tag_through" ("id" INTEGER NOT

    NULL PRIMARY KEY, "post_id" INTEGER NOT NULL, "tag_id" INTEGER NOT NULL, FOREIGN KEY ("post_id") REFERENCES "post" ("id"), FOREIGN KEY ("tag_id") REFERENCES "tag" ("id")) by ABE Hiroki aka hATrayflood
  15. 2018/7/28 ⻑野Python会 with NSEG tag1 = Tag(label="python") tag1.save() tag2 =

    Tag(label="peewee") tag2.save() post.tags.add(tag1) post.tags.add([tag2]) by ABE Hiroki aka hATrayflood
  16. 2018/7/28 ⻑野Python会 with NSEG File "test.py", line 81, in <module>

    posts.count() File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 1574, in inner return method(self, database, *args, **kwargs) File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 1829, in count return Select([clone], [fn.COUNT(SQL('1'))]).scalar(database) File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 1574, in inner return method(self, database, *args, **kwargs) File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 1815, in scalar row = self.tuples().peek(database) File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 1574, in inner return method(self, database, *args, **kwargs) File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 1802, in peek rows = self.execute(database)[:n] File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 1574, in inner return method(self, database, *args, **kwargs) File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 1645, in execute return self._execute(database) File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 1796, in _execute cursor = database.execute(self) File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 2653, in execute return self.execute_sql(sql, params, commit=commit) File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 2647, in execute_sql self.commit() File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 2438, in __exit__ reraise(new_type, new_type(*exc_args), traceback) File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 177, in reraise raise value.with_traceback(tb) File "c:\Program Files\Python36\lib\site-packages\peewee.py", line 2640, in execute_sql cursor.execute(sql, params or ()) peewee.OperationalError: no such column: t1.tags by ABE Hiroki aka hATrayflood
  17. 2018/7/28 ⻑野Python会 with NSEG query = Post.select() thru = Post.tags.get_through_model()

    alias1 = thru.alias() query = query.switch(Post).join(alias1)\ .where(alias1.tag==tag1) alias2 = thru.alias() query = query.switch(Post).join(alias2)\ .where(alias2.tag==tag2) query.sql() by ABE Hiroki aka hATrayflood
  18. 2018/7/28 ⻑野Python会 with NSEG ('SELECT "t1"."id", "t1"."user_id", "t1"."text", "t1"."posted_at" FROM

    "post" AS "t1" INNER JOIN "post_tag_through" AS "t2" ON ("t2"."post_id" = "t1"."id") INNER JOIN "post_tag_through" AS "t3" ON ("t3"."post_id" = "t1"."id") WHERE (("t2"."tag_id" = ?) AND ("t3"."tag_id" = ?))', [1, 2]) by ABE Hiroki aka hATrayflood
  19. 2018/7/28 ⻑野Python会 with NSEG db = SqliteDatabase("test.db") class User(Model): name

    = CharField() email = CharField() class Meta: database = db by ABE Hiroki aka hATrayflood
  20. 2018/7/28 ⻑野Python会 with NSEG models.py: from peewee import * db

    = MySQLDatabase(None) class BaseModel(Model): class Meta: database = db class User(BaseModel): name = CharField() email = CharField() by ABE Hiroki aka hATrayflood
  21. 2018/7/28 ⻑野Python会 with NSEG web.py: from bottle import * from

    models import * app = Bottle() db.init("glnagano_python", host="localhost", port=3306, \ user="glnagano_python", password="glnagano_python") @app.hook("before_request") def before_request(): db.connect() @app.hook("after_request") def after_request(): db.close() @app.route('/') def index(): return "%d users exists" % User.select().count() run(app, host='0.0.0.0', debug=True) by ABE Hiroki aka hATrayflood
  22. 2018/7/28 ⻑野Python会 with NSEG models_flask.py: from peewee import * from

    playhouse.flask_utils import * db = FlaskDB() class User(db.Model): name = CharField() email = CharField() by ABE Hiroki aka hATrayflood
  23. 2018/7/28 ⻑野Python会 with NSEG web_flask.py: from flask import * from

    models_flask import * app = Flask(__name__) app.config.from_json("config.json") db.init_app(app) @app.route('/') def index(): return "%d users exists" % User.select().count() app.debug = True app.run(host="0.0.0.0") by ABE Hiroki aka hATrayflood
  24. 2018/7/28 ⻑野Python会 with NSEG config.json: { "DATABASE":{ "engine":"MySQLDatabase", "name":"glnagano_python", "host":"localhost",

    "port":3306, "user":"glnagano_python", "password":"glnagano_python", "charset":"utf8mb4"} } by ABE Hiroki aka hATrayflood
  25. 2018/7/28 ⻑野Python会 with NSEG ・リンク集 twitter @hATrayflood http://twitter.com/hATrayflood github coleifer/peewee

    https://github.com/coleifer/peewee peewee 3.6.4 documentation http://docs.peewee-orm.com/en/latest/ SQLiteの⾃動インクリメント - しょぼんメモリ (´・ω・`) https://shobon.hatenablog.com/entry/2014/03/30/210444 by ABE Hiroki aka hATrayflood
  26. 2018/7/28 ⻑野Python会 with NSEG Field types table http://docs.peewee-orm.com/en/latest/peewee/models.html#field-types-table Field initialization

    arguments http://docs.peewee-orm.com/en/latest/peewee/models.html#field-initialization-arguments Query operators http://docs.peewee-orm.com/en/latest/peewee/query_operators.html Flask Utils http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#flask-utils Bottle Peewee https://github.com/klen/bottle-peewee by ABE Hiroki aka hATrayflood