def generate_tables(): if not db.engine: db.create_engine('awesome.db') sql = lambda x: ''.join(x().__sql__.split('\n')[1:]) db.update(sql(User)) db.update(sql(Blog)) db.update(sql(Comment))
def generate_tables(): if not db.engine: db.create_engine('awesome.db') sql = lambda x:''.join(x().__sql__.split('\n')[1:]) db.update(sql(User)) db.update(sql(Blog)) db.update(sql(Comment))
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'this is test!' from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='test') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
def datetime_filter(t): delta = int(time.time() - t) if delta < 60: return u'1分钟前' if delta < 3600: return u'%s分钟前' % (delta // 60) if delta < 86400: return u'%s小时前' % (delta // 3600) if delta < 604800: return u'%s天前' % (delta // 86400) dt = datetime.fromtimestamp(t) return u'%s年%s月%s日' % (dt.year, dt.month, dt.day) # init db: db.create_engine(**configs.db) # init wsgi app: wsgi = WSGIApplication(os.path.dirname(os.path.abspath(__file__))) template_engine = Jinja2TemplateEngine( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')) template_engine.add_filter('datetime', datetime_filter) wsgi.template_engine = template_engine import urls wsgi.add_interceptor(urls.user_interceptor) wsgi.add_interceptor(urls.manage_interceptor) wsgi.add_module(urls)
''' A WSGI application entry. ''' import logging; logging.basicConfig(level=logging.INFO) import os from transwarp import db from transwarp.web import WSGIApplication, Jinja2TemplateEngine from config import configs # init db: db.create_engine(**configs.db) # init wsgi app: wsgi = WSGIApplication(os.path.dirname(os.path.abspath(__file__))) template_engine = Jinja2TemplateEngine(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')) wsgi.template_engine = template_engine import urls wsgi.add_interceptor(urls.user_interceptor) wsgi.add_interceptor(urls.manage_interceptor) wsgi.add_module(urls) if __name__ == '__main__':
#!/usr/bin/env python # -*- coding: utf-8 -*- from models import User, Blog, Comment from transwarp import db __author__ = 'Huxh' db.create_engine(user='******', password='******', database='awesome') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
def datetime_filter(t): delta = int(time.time() - t) if delta < 60: return u'1分钟前' if delta < 3600: return u'%s分钟前' % (delta // 60) if delta < 86400: return u'%s小时前' % (delta // 3600) if delta < 604800: return u'%s天前' % (delta // 86400) dt = datetime.fromtimestamp(t) return u'%s年%s月%s日' % (dt.year, dt.month, dt.day) db.create_engine(configs.db['user'],configs.db['password'],configs.db['database'],configs.db['host'])#,**configs.db) # init wsgi app: wsgi = WSGIApplication(os.path.dirname(os.path.abspath(__file__))) template_engine = Jinja2TemplateEngine(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')) template_engine.add_filter('datetime',datetime_filter) wsgi.template_engine = template_engine import urls wsgi.add_interceptor(urls.user_interceptor) wsgi.add_interceptor(urls.manage_interceptor) wsgi.add_module(urls) # add_module(urls)会检查urls这个模块里所有的属性对象,如果该属性对象是callable且有__web_route__和__web_method__属性(通常是被get和post装饰过),
#!/usr/bin/env python # -*- coding: utf-8 -*- from models import User, Blog, Comment from transwarp import db print '-----test_db.py-----' db.create_engine(user='******', password='******', database='blogdb') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
from models import User, Blog, Comment import logging from transwarp import db logging.basicConfig(level = logging.DEBUG) db.create_engine(user = '******', password = '******', database = 'myblog') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id print 'create time:', u.created_at u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_by('where email=?', '*****@*****.**') print 'find user:', u2
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') console.setFormatter(formatter) # 将定义好的console日志handler添加到root logger logging.getLogger('').addHandler(console) from models import User, Blog, Comment from transwarp import db @db.with_transaction def test(): u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:'******'__main__': db.create_engine(user='******', password='******', database='awesome') test() print time.time() , time.strptime()
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'tiger' from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='awesome') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name # u1.delete() # # u2 = User.find_first('where email=?', '*****@*****.**') # print 'find user:', u2
#!/usr/bin/env python # -*- coding:utf-8 -*- from models import User,Blog,Comment from transwarp import db db.create_engine(user='******',password='******',database='awesome-webapp') u = User(name='Test',email='*****@*****.**',password='******',image='about:blank') u.insert() print 'new user id:',u.id u1 = User.find_first('where email=?','*****@*****.**') print 'find user\'s name:',u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
# paramas[k] = kw.pop(k, v) # print paramas[k] # paramas.update(kw) # print paramas # # create_engine('comon','gloryn','mysql') from models import User, Blog, Comment from transwarp import db import time db.create_engine(user='******', password='******', database='awesome') u = User(name='Test3', email='[email protected]', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name # u1.delete() # # time.sleep(1) # u2 = User.find_first('where email=?', '*****@*****.**') # print 'find user:', u2
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-08-26 14:10:07 # @Author : djj ([email protected]) # @Link : ${link} # @Version : $Id$ __author__ = "SolrSky" from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='awesome', host='localhost', port='3306') u = User(name='Test', email='*****@*****.**', password='******', image='http://img.qfc.cn/upload/01/certificate/02/0d/705808.jpg') u.insert() print "new user id:", u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: gaopeng # @Date: 2017-11-13 17:30:00 # @Last modified by: gaopeng # @Last modified time: 2018-01-22 17:06:11 from models import User, Blog, Comment from transwarp import db db.create_engine('root', 'root', 'test') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name # u1.delete() # # u2 = User.find_first('where email=?', '*****@*****.**') # print 'find user:', u2
user_image = StringField(ddl = 'varchar(50)') name = StringField(ddl = 'varchar(50)') summary = StringField(ddl = 'varchar(200)') content = TextField() created_at = FloatField(updatable = False, default = time.time) class Comment(Model): __table__ = 'comments' id = StringField(primary_key = True, default = db.next_id, ddl = 'varchar(50)') blog_id = StringField(updatable = False, ddl = 'varchar(50)') user_id = StringField(updatable = False, ddl = 'varchar(50)') user_name = StringField(ddl = 'varchar(50)') user_image = StringField(ddl = 'varchar(500)') content = TextField() created_at = FloatField(updatable = False, default = time.time) if __name__ == '__main__': db.create_engine('root', 'password', 'myblog') db.update('drop table if exists users') db.update('drop table if exists blogs') db.update('drop table if exists comments') db.update(User().__sql__()) db.update(Blog().__sql__()) db.update(Comment().__sql__())
#!/usr/bin/env python from models import User,Blog,Comment from transwarp import db import logging if __name__ == '__main__': logging.basicConfig(level=logging.INFO) db.create_engine(user='******',password='******',database='awesome') u = User(name='Test',email='*****@*****.**',passwd='987654321',image='about:blank') u.insert() print 'new user id:',u.id u1 = User.find_first('where email=?','*****@*****.**') print 'find user\'s name:',u1.name u1.delete() u2 = User.find_first('where email=?','*****@*****.**') print 'find user\'s name:',u2.name
#!/usr/bin/env python # -*- coding: utf-8 -*- from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='awesome') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
#!/usr/bin/python # -*- coding: UTF-8 -*- from models import departments, students, question from transwarp import db db.create_engine(user='******', password='******', database='questionaire') try: ques = question(title=u'对于本学期的文计课,你有什么期望或建议(教学内容、教学方式等)', option=u'', type=2, score=5) ques.insert() except Exception, e: print e try: ques = question(title=u'在哪里使用计算机', option=u'家里台式机;笔记本电脑;网吧;图书馆;计算中心;院系计算机房', type=1, score=5) ques.insert() except Exception, e: print e try: ques = question(title=u'使用计算机的程度是', option=u'很少使用;不熟练;还可以吧;熟练;很熟练') ques.insert() except Exception, e: print e # try: # department = departments(departmentID='0048', departmentName='EECS') # department.insert()
#!/usr/bin/env python # -*- coding: utf-8 -*- from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='xblog') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') print hasattr(u, '__mappings__') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
# -*- coding: utf-8 -*- __author__ = 'ghost' from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', passwd='', db='webapp') u = User(email='*****@*****.**', passwd='111111', admin=True, nickname='rsj217', avatar='') print u u.insert() # uu = User.find_by("WHERE admin=1") # print uu[0].passwd
#!/usr/bin/python #coding:utf-8 # test_db.py __author = 'HSING LI' from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='blog', host='192.168.204.201') u = User(name='person', email='*****@*****.**', password='******', image='about:blank') u.insert() print('new user id:', u.id) u1 = User.find_first('where email=?', '*****@*****.**') print('find user\'s name:', u1.name) # u1.delete() # # u2 = User.find_first('where email=?', '*****@*****.**') # print('find user:', u2)
''' Created on Jun 11, 2016 @author: zlp ''' from models import User, Blog, Comment from transwarp import db import logging db.create_engine(user='******', password='******', database='awesome') u = User(name='Test', email='test@example', password='******', image='about:blank') # it can only be inserted once, in the DB, Email column is distinct, if insert multiple time, it will return error message. try: u.insert() except Exception,e: logging.warning('It seems that the same user has been inserted, %s' % e) print 'new user id:', u.id #Here I add to print the cls name u1 = User.find_first('where email=?', '*****@*****.**') print u1
#!/usr/bin/env python # -*- coding: utf-8 -*- from transwarp import db db.create_engine(user='******', password='', database='test', host='127.0.0.1', port='3307')
#!/usr/bin/env python # -*- coding:utf-8 -*- from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='awesome-webapp') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Michael Liao' from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='awesome') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name #u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'Jeffwu' from models import User, Blog, Comment from transwarp.orm import StringField,Field from transwarp import db db.create_engine(user='******', passwd='', database='awesome') u = User(name='Test', email='*****@*****.**', passwd='1234567890', image='about:blank') print isinstance(u.name,StringField) #u.insert() #print 'new user id:', u.id #u1 = User.find_first('where email=?', '*****@*****.**') #print 'find user\'s name:', u1.name #u1.delete()
#!/usr/bin/env python # -*- coding: utf-8 -*- from models import Blog, comment, testuser2 from transwarp import db db.create_engine(user='******', password='******', database='test2') u = testuser2(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = testuser2.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = testuser2.find_first('where email=?', '*****@*****.**') print 'find user:', u2
#coding:utf8 from models import User, Blog, Comment from transwarp import db #开启数据库引擎,连接数据库 db.create_engine(user='******', password='******', database='test') #实例化一个user类,做好形成表格的准备,进行初始化Model类--》ModelMetalClass采集属性字段,然后通过Model类的函数来进行表格数据操作 u = User(name='Test', email='*****@*****.**', password='******', image='about:blank', admin=False) print User().__sql__() #形成表格之前,判断此表格是否存在,存在下drop db.update('drop table if exists user') #形成表格后进行字段栏的构建,手写创建表的sql脚本 #db.update('create table user (id varchar(50) primary key, email text, password text, admin text, name text, image text, create_at float)') #表比较多话,用Model对象通过脚本直接生成sql脚本 db.update(User().__sql__()) #字段栏形成后,进行数据的插入 u.insert() print 'new user id:', u.id #查询 u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name #删除
__author__= '*****@*****.**' import sys import hashlib from models import User,Blog,Comment from transwarp import db from transwarp.orm import Model import logging logger = logging.getLogger(__name__) logger = logging.getLogger(__name__) LOG_FORMAT = ('%(levelname) -10s %(process)d %(asctime)s %(filename)-10s %(lineno) -5d: %(message)s') logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) db.create_engine('web_user', 'web_pwd', 'web_db') Model.create_all() u = User(name='admin',admin=1, email='*****@*****.**', image='about:blank') u1 = User(name='jsong', email='*****@*****.**', image='about:blank') u.insert() u1.insert() b = Blog(id=1,user_id='00153431774194282fc64ed618a485e83a2f227bce4da45000', user_name='jsong', name='test blog', summary='test blog:this is a blog about test',context="测试博客") b2 = Blog(id=2,user_id='00153431774194282fc64ed618a485e83a2f227bce4da45000', user_name='jsong', name='test blog2', summary='test blog:this is a blog about test',context="测试博客2") b.insert() b2.insert()
#!/usr/bin/env python # -*- coding: utf-8 -*- from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='xblog') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') print hasattr(u,'__mappings__') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='awesome') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'K.Lee' from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='kblog') testUser = User(name='Test', email='*****@*****.**', password='******', image='about:blank') testUser.insert() print 'new user id:', testUser.id user = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name', user.name user.delete() user2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', user2
#!/usr/bin/env python # coding=utf-8 #db.py from transwarp import db db.create_engine(user='******',password='******',database='littlesnail',host='127.0.0.1',port=3306) users = db.select('select * from user') n = db.update('insert into user(id,name) values(?,?)',4,'Jack') with db.connection(): db.select('...') db.update('...') db.update('...') #数据库引擎对象: class _Engine(object): def __init__(self,connect): self.connect = connect def connect(self): return self.connect() engine = None #持有数据库连接的上下文对象: class _DbCtx(threading.local): def __init__(self): self.connection = None self.transactions = 0 def is_init(self): return not self.connection is None def init(self): self.connection = LasyConnection() self.transactions = 0 def cleanup(self): self.connection,cleanup()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author: songtailun """ from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='python_web') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
#!/usr/bin/python # -*- coding: utf-8 -*- from transwarp import db db.create_engine(user="******", passwd="520119", db="testdb", host="127.0.0.1", port="3306") users = db.select("select * from user")
import models.models from transwarp import db db.create_engine(user='******', password='******', database='test') u = User(email='*****@*****.**', name='wyq', password='******', image='about:blank') u.insert()
pk = self.__primary_key__.name args.append(getattr(self, pk)) db.update('update `%s` set %s where %s=?' % (self.__table__, ','.join(L), pk), *args) return self def delete(self): self.pre_delete and self.pre_delete() pk = self.__primary_key__.name args = (getattr(self, pk), ) db.update('delete from `%s` where `%s`=?' % (self.__table__, pk), *args) return self def insert(self): self.pre_insert and self.pre_insert() params = {} for k, v in self.__mappings__.iteritems(): if v.insertable: if not hasattr(self, k): setattr(self, k, v.default) params[v.name] = getattr(self, k) db.insert('%s' % self.__table__, **params) return self if __name__=='__main__': logging.basicConfig(level=logging.DEBUG) db.create_engine('www-data', 'www-data', 'test') db.update('drop table if exists user') db.update('create table user (id int primary key, name text, email text, passwd text, last_modified real)') import doctest doctest.testmod()
#!/usr/bin/env python # -*- coding: utf-8 -*- from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='pywebapp') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name #u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'learned by xiaojian' from models import User, Blog, Comment import time, logging from transwarp import db logging.basicConfig(level=logging.INFO) db.create_engine(user='******', password='******',database='test') u = User(name='Test', email = '*****@*****.**', password='******',image='about:blank') db.update(' %s ' % u.__sql__() ) print User.__table__ u.insert() print 'new user id:',u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find ',u1.name #u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find :',u2
#!/usr/bin/env python # -*- coding: utf-8 -*- from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='test', host='121.42.58.105') u = User(id=10190, name='Test', email='*****@*****.**', password='******') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Wang Shaohua' from models import User from transwarp import db db.create_engine(user='******', password='******', database='awesome') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name # u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
#!/usr/bin/env python # -*- coding: utf-8 -*- from transwarp import db from models.allmodels import User, Blog, Comment from transwarp.web import * from conf.config import configs import random db.create_engine(**configs['db']) # b = Blog() # c = Comment # # b.save() # c.save() users_ids = User.all() for user in users_ids: print user # blogs = Blog.all() # print '-all blogs:' # print blogs # exit() # 生成10个blogs # for i in range(4,5): # user = random.sample(users_ids, 1)[0] # print 'add blogs {}'.format(i) # print user # title = 'Google ' # summary = 'After coming up with a really good recipe within Google. Read more' # content = 'We baked it, and our eager taste-testers—Googlers ready and willing to sacrifice for science by eating the cookies—tasted it and gave it a numerical score relative to store-bought cookie samples. We fed that rating back into the system, which learned from the rating and adjusted those “knobs” to create a new recipe. We did this dozens of times—baking, rating, and feeding it back in for a new recipe—and pretty soon the system got much better at creating tasty recipes.' #
import os import sys parent_path = os.path.dirname(sys.path[0]) + '/transwarp' parent_path1 = os.path.dirname(sys.path[0]) + '/' if parent_path not in sys.path: sys.path.append(parent_path) if parent_path1 not in sys.path: sys.path.append(parent_path1) from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='gbd_spider') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name #u1.delete()
#!/usr/bin/env python # -*- coding: utf-8 -*- from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='awesome') # u0 = User(name = 'Test',email = '*****@*****.**',password = '******',image = 'about:blank') # u0.insert() # u1 = User(name = 'Test001',email = '*****@*****.**',password = '******',image = 'about:blank') # u1.insert() # u2 = User(name = 'Test002',email = '*****@*****.**',password = '******',image = 'about:blank') # u2.insert() # u3 = User(name = 'Test003',email = '*****@*****.**',password = '******',image = 'about:blank') # u3.insert() # b1 = Blog(user_id = '001',user_name = 'lly001',user_image = '',name = '这是一条博客',sunmary = '总结的话',content = '这条博客是一条测试博客,为了测试web是否能正常显示数据库的内容啦啦啦啦啦啦啦啦啦啦啊啊',create_at = 'beijing') # b1.insert() # b2 = Blog(user_id = '002',user_name = 'lly002',user_image = '',name = '这是一条博客',sunmary = '总结的话',content = '这条博客是一条测试博客,为了测试web是否能正常显示数据库的内容啦啦啦啦啦啦啦啦啦啦啊啊',create_at = 'beijing') # b2.insert()
sql = ['-- schema.sql'] sql.append('-- help:') sql.append('-- Login MySQL: mysql -u root -p') sql.append('-- Execute Script: source /path/to/schema.sql') sql.append('drop database if exists test;') sql.append( 'create database test default charset utf8 collate utf8_general_ci;' ) sql.append('use test;') sql.append( 'create user if not exists \'www-data\'@\'localhost\' identified by \'www-data\';' ) sql.append( '-- grant select, insert, update, delete on test.* to \'www-data\'@\'localhost\' identified by \'www-data\';' ) sql.append( 'grant all privileges on test.* to \'www-data\'@\'localhost\' identified by \'www-data\';' ) sql.append(User().__sql__()) sql.append(Blog().__sql__()) sql.append(Comment().__sql__()) sql.append(Attachment().__sql__()) f.write('\n'.join(sql)) # 执行doctest import logging logging.basicConfig(level=logging.DEBUG) from transwarp import db db.create_engine('www-data', 'www-data', 'test') import doctest doctest.testmod()
if data_table: return data_table.index else: return 0 @classmethod def add_table(cls,index): r = redis.Redis() dt = Data() dt.create_table(sub_name = str(index)) r.set("last_data_table_index",index) new_table = Data_Table_Map() new_table.end_time = time.time() new_table.index = index new_table.insert() @classmethod def get_tables(cls, start_time, end_time): return cls.find_by('where start_time<? and end_time>?', end_time, start_time) if __name__=="__main__": db.create_engine('sonic513', 'sonic513', 'tobacco_monitor', host='127.0.0.1',port='3306') dtm = Data_Table_Map() print dtm.find_first("where 'index'=?",index)
from urls import web import ConfigParser from transwarp import db config_file = 'E:\pythonproject\webapp\www\config.ini' cfg = ConfigParser.ConfigParser() cfg.read(config_file) db.create_engine(**dict(cfg.items('db'))) if __name__ == '__main__': with db.conn(): web.run()
import os, sys reload(sys) sys.setdefaultencoding('utf8') sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'site-packages.zip')) import logging; logging.basicConfig(level=logging.INFO) from transwarp import db from transwarp.web import WSGIApplication, Jinja2TemplateEngine from config import configs from filters import datetime_filter, rssdate_filter, markdown_filter # 初始化数据库 db.create_engine(**configs['db']) # 创建一个WSGIApplication wsgi = WSGIApplication(os.path.dirname(os.path.abspath(__file__))) # 初始化Jinja2模版引擎 template_engine = Jinja2TemplateEngine(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')) # 把filter添加到jinja2,filter本身是一个函数对象 template_engine.add_filter('datetime', datetime_filter) template_engine.add_filter('rssdate', rssdate_filter) template_engine.add_filter('html', markdown_filter) wsgi.template_engine = template_engine # 加载url中的函数
# !/usr/bin/env python # -*- coding:utf-8 -*- from models import User, Blog, Comment from transwarp import db db.create_engine(user='******', password='******', database='awesomeblog') # u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') # u.insert() # print 'new user id:', u.id # u1 = User.find_first('where email=?', '*****@*****.**') # print 'find user\'s name:', u1.name # u1.delete() # u2 = User.find_first('where email=?', '*****@*****.**') # print 'find user\'s name:', u2.name # summary = '今天上午,魅族宣布将于6月2日在北京国家会议中心召开魅蓝新品发布会,如果不出什么意外花,新一代魅蓝系列手机就要跟我们见面了。下午,又有用户在微博上曝光了疑似魅蓝Note 2的真机照。谍照显示,虽然该机采用了实体Home键,但并不支持指纹识别功能。而现在,魅族副总裁李楠则在微博上确认了魅蓝新机即将发布的消息,而且他还表示,这款魅蓝确实会配备“腰圆”键,但并不支持指纹识别功能。' # content = '那么,好端端取消小圆圈,换成Home键干啥呢?李楠表示这是来“革Android系统返回键命”的,看来魅族又要在操作方式上有所创新了。今天上午,魅族宣布将于6月2日在北京国家会议中心召开魅蓝新品发布会,如果不出什么意外花,新一代魅蓝系列手机就要跟我们见面了。下午,又有用户在微博上曝光了疑似魅蓝Note 2的真机照。谍照显示,虽然该机采用了实体Home键,但并不支持指纹识别功能。而现在,魅族副总裁李楠则在微博上确认了魅蓝新机即将发布的消息,而且他还表示,这款魅蓝确实会配备“腰圆”键,但并不支持指纹识别功能。' # name = 'Meizu' # user_name = 'Administrator' # b = Blog(name=name, user_name=user_name, content=content, summary=summary) # b.insert() # summary = '小米已成立5年之久,旗下的智能手机以及平板电脑正在中国热销。现在,该公司打算进军欧美市场,但准备销售的产品并非国人熟知的手机和平板。周一夜间,小米针对美国消费者的在线商店正式上线,各种配件陈列其中,包括移动电源、售价为80美元的Mi耳机以及15美元的Mi Band健身追踪器。周二,该商店还将出现在英国、德国以及法国。' # content = '此举意味着小米向进军西方市场迈出了关键一步。过去,小米一直以低价智能手机厂商的形象示人,在包括印度、马来西亚以及印度尼西亚在内的发展中国家销售自己的产品但小米的野心不仅止于此。小米全球副总裁雨果·巴拉(Hugo Barra)于三月表示,公司将自身定位为一个引领生活方式的品牌。去年12月,小米成为世界上最具价值的初创公司,在成功融得11亿美元之后,公司的估值达到450亿美元。小米对中国消费者产生了巨大的吸引力,使得人们经常将其拿来与苹果比较。小米创始人和CEO雷军的一举一动都受到已逝苹果CEO史蒂夫·乔布斯的影响。小米的新品通常在数分钟内即告售罄。例如,4月,200万台智能手机在12小时内便被消费者一扫而光。今年一季度,小米在中国市场售出1350万台智能手机,仅次于苹果,后者的数字为1450万台。而华为、联想以及三星则落在小米身后。' # name = 'Xiaomi' # user_name = 'Administrator' # b = Blog(name=name, user_name=user_name, content=content, summary=summary)
# web app 里面又很多地方都要访问数据库,访问数据库需要创建数据库连接、游标对象,然后执行SQL语句,最后处理异常、清理资源。这些访问数据库代码 # 如果分散到每个函数中,势必无法维护,也不利于代码复用。 # 此外,在一个web app中,又多个用户会同时访问,系统以多进程或多线程的模式来处理每个用户的请求,假设以多线程为例,每个线程在数据库访问时,都 # 必须创建仅属于自己的连接,对别的线程不可见,否则,就会造成数据库操作混乱 # 所以我们还要创建一个简单可靠的数据库访问模型,在一个线程中能够安全又简单的操作数据库 # 为什么不选择SQLAlchemy?SQLAlchemy太庞大,过渡地面向对象设计导致API太复杂 # 所以我们决定自己设计一个封装基本的select、insert、update和delete的db模块:transwarp.db # 设计 db 接口 # 设计底层模块的原则是,根据上层调用者设计简单易用的 API 接口,然后实现模块内部代码 # 假设 transwarp.db 模块已经编写完毕,我们希望以这样的方式来调用他: # 首先初始化数据库连接信息,通过 create_engine() 函数: from transwarp import db db.create_engine(user='******', password='******', database='test', host='127.0.0.1', port=3306) # 然后就可以直接操作 SQL 了 # 如果需要做一个查询,可以直接调用 select() 方法,返回的是 list, 每个元素是用 dict 标识的对应的行 users = db.select('select * from suer') # users=> # [ # {"id":1,"name":"Jack"}, # {"id":2,"name":"Bob"} # ] # 如果要执行 insert update deletecaozuo ,执行 update() 方法,返回受影响的行数 # n=db.update('update users set name = "Lily" where id in (?,?',4,5) # update() 函数签名为 update(slq,*args) # 统一用?作为占位符,并传入可变参数来绑定,从根本上避免 SQL 注入共计 # 每个 select() 和 update() 调用,都隐含地自动打开并关闭了数据库连接,这样上层调用者完全不必关心数据库地层连接
#!/usr/bin/python # -*- coding: utf-8 -*- from transwarp import db db.create_engine(user='******', passwd='520119', db='testdb',\ host='127.0.0.1', port=3306) users = db.select('select * from VFORBOX') for i in users: print i n = db.update('insert into VFORBOX(NAME, AGE, SEX) values(?, ?, ?)',\ 'LXF', 4, 'M')
def connect_db(): import transwarp.db as dbutil dbutil.create_engine('sonic513', 'sonic513', 'co2_monitor', port=3306)
if data_table: return data_table.index else: return 0 @classmethod def add_table(cls, index): r = redis.Redis() dt = Data() dt.create_table(sub_name=str(index)) r.set("last_data_table_index", index) new_table = Data_Table_Map() new_table.end_time = time.time() new_table.index = index new_table.insert() @classmethod def get_tables(cls, start_time, end_time): return cls.find_by('where start_time<? and end_time>?', end_time, start_time) if __name__ == "__main__": db.create_engine('sonic513', 'sonic513', 'tobacco_monitor', host='127.0.0.1', port='3306') dtm = Data_Table_Map() print dtm.find_first("where 'index'=?", index)
#!/usr/bin/env python # encoding:utf-8 __author__ = 'YJX' __data__ = 2016 / 6 / 17 from models import User, Blog, Comment from transwarp import db if __name__ == '__main__': db.create_engine(user='******', password='******', database='awesome') u = User(name='Test', email='*****@*****.**', password='******', image='about:blank') u.insert() print 'new user id:', u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find user\'s name:', u1.name u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find user:', u2
content = TextField() created_at = FloatField(default=time.time()) class Comment(Model): __table__ = 'Comment' id = IntegerField(primary_key=True) blog_id = StringField(ddl='varchar(50)') user_id = StringField(ddl='varchar(50)') user_name = StringField(ddl='varchar(50)') user_image = StringField(ddl='varchar(500)') content = TextField() if __name__ == '__main__': db.create_engine('root', 'cheng', 'awesome') with db.conn(): db.update('drop table if exists User') db.update('drop table if exists Blog') db.update('drop table if exists Comment') db.update(User.__sql__) db.update(Blog.__sql__) db.update(Comment.__sql__) u = User(id=0, name='cwyj', email='*****@*****.**', password='******', admin=True) u2 = User(name='cheng', email='*****@*****.**', password='******') b = Blog(user_id=0, user_name='cwyj',