def main(self, **kwargs): kwargs['delimited'] = 'length' self.logger.info("Running streamer, tracking list as follows: %s" % kwargs.get("track")) url = self.url + "/statuses/filter.json" data = self.oauth_request(url, kwargs) headers = {"Content-Type": "application/x-www-form-urlencoded"} connection = httplib.HTTPSConnection("stream.twitter.com") connection.request( method = "POST", url = "/1.1/statuses/filter.json", body = urllib.urlencode(data), headers = headers) self.response = connection.getresponse() while True: length = self._get_buffer() if length: update = self.response.read(length) update = json.loads(update) tw = Tweet(fulldata=update) tw.save() self.logger.info("Added new tweet! %s" % tw._data.get("_id")) u = User(fulldata=update.get("user")) u.save() self.logger.info("Added new user! %s" % u._data.get("_id")) else: self.logger.info("Pinging.. streamer::main is waiting for an update")
def main(self, **kwargs): kwargs['delimited'] = 'length' self.logger.info("Running streamer, tracking list as follows: %s" % kwargs.get("track")) url = self.url + "/statuses/filter.json" data = self.oauth_request(url, kwargs) headers = {"Content-Type": "application/x-www-form-urlencoded"} connection = httplib.HTTPSConnection("stream.twitter.com") connection.request(method="POST", url="/1.1/statuses/filter.json", body=urllib.urlencode(data), headers=headers) self.response = connection.getresponse() while True: length = self._get_buffer() if length: update = self.response.read(length) update = json.loads(update) tw = Tweet(fulldata=update) tw.save() self.logger.info("Added new tweet! %s" % tw._data.get("_id")) u = User(fulldata=update.get("user")) u.save() self.logger.info("Added new user! %s" % u._data.get("_id")) else: self.logger.info( "Pinging.. streamer::main is waiting for an update")
async def testInsert(loop): await orm.orm.create_pool(loop=loop) u = User(name='Test', email='*****@*****.**', passwd='1234567890', image='about:blank') await u.save()
def buy_vip_interface(back_dic, ): username = back_dic.get('username') user_obj = User().select(whereStr="name = '{}'".format(username)) if user_obj: user_obj[0].is_vip = 1 user_obj[0].update() send_dic = {'msg': '购买成功,会员爸爸!'} else: send_dic = {'msg': '操作失败!'} return send_dic
def post(self): """ 用户登录,获取token """ username = self.body_arguments.get('username') password = self.body_arguments.get('password') if not username or not password: raise HTTPError( status_code=400, reason= 'Missing arguments,please check your username & password') try: user, error_reason = ldap.valid_user(username, password) except LDAPException as e: app_log.error(e) raise HTTPError(status_code=500, reason='ldap error') if not user: raise HTTPError(status_code=400, reason=error_reason) token = jwt.encode(payload=user, key=settings['token_secret'], algorithm='HS256').decode("utf-8") # update info with session_scope(self.session) as ss: # update user user_instance = ss.query(User).filter( User.username == user['username']).one_or_none() if not user_instance: user_instance = User(username=user['username']) ss.add(user_instance) ss.flush() # update department department = user.pop('department_name', None) # delete old user-department ss.query(UserDepartment).filter( UserDepartment.user_id == user_instance.id).delete() if department is not None: for dep_name in department: department_instance = ss.query(Department).filter( Department.name == dep_name).one_or_none() if not department_instance: department_instance = Department(name=dep_name) ss.add(department_instance) ss.flush() ud = UserDepartment(extra_data="some data") ud.department_id = department_instance.id ud.user_id = user_instance.id ss.add(ud) self.render_json_response(code=200, msg='OK', res={'token': token})
def register_interface(back_dic,): # 面条版: 业务逻辑 username = back_dic.get('username') user_obj = User(name=username).select(whereStr ="name = {}".format(username)) if not user_obj: password = back_dic.get('password') # 创建数据 user_obj = User(name=username, password=common.get_md5(password), user_type=back_dic.get('user_type'), register_time=str(datetime.datetime.now()), is_vip=0, is_locked=0 ) user_obj.save() send_dic = { 'flag': True, 'msg': '注册成功!' } else: send_dic = {'flag': False, 'msg': '用户已存在!'} return send_dic
def login_interface(back_dic,): username = back_dic.get('username') usertype = back_dic.get('user_type') # 判断用户是否存在 user_list = User(name=username).select(whereStr ="name = {} and user_type = '{}' ".format(username,str(usertype))) if user_list: user_obj = user_list[0] password = back_dic.get('password') # 判断密码是否正确 if common.get_md5(password) == user_obj.password: # 登录成功后记录状态 # cookies, session # 一个加密后的随机字符串 session = common.get_session(username) addr = back_dic.get('addr') # 保存session到服务端 # [session, user_obj.user_id] # [afwagawgwaawgwaga, 1] # 把用户session字符串与id写入user_data文件中 # user_data.mutex.acquire() user_data.online_user[addr] = [session, user_obj.id] # user_data.mutex.release() send_dic = { 'flag': True, 'msg': '登录成功', 'id': user_obj.id, 'session': session, 'is_vip': user_obj.is_vip } else: send_dic = { 'flag': False, 'msg': '密码错误' } else: send_dic = { 'flag': False, 'msg': '用户不存在!' } return send_dic
def post(self): """ add user object argument should be list :return: """ arguments = self.body_arguments if not arguments: raise HTTPError(status_code=400, reason="json arguments is invalid") arguments.pop('id', None) with session_scope() as ss: user_instance = User(arguments) ss.add(user_instance) ss.flush() _id = user_instance.id res = ss.query(User).get(_id).to_dict() self.render_json_response(code=200, msg="OK", id=_id, res=res)
def registration_page(): form = forms.RegistrationForm() if form.validate_on_submit(): user = User(form.name.data, form.email.data, form.password.data) s = db_session.create_session() try: s.add(user) s.commit() except IntegrityError: return render_template( 'register.html', title='Регистрация', form=form, message='Пользователь с таким E-mail уже существует!') except Exception as e: print(e) return render_template('register.html', title='Регистрация', form=form, message='Произошла неизвестная ошибка.') finally: s.close() return redirect('/login') return render_template('register.html', title='Регистрация', form=form)
from flask import Flask, render_template, redirect, abort, request
elif num_completed == 2: first_name = 'Foghorn' last_name = 'Leghorn' else: first_name = 'Demo' last_name = 'User' # create user try: user = User.objects.get(username__in=['user' + str(num_completed), 'demo']) except User.DoesNotExist: if num_completed == 3: username = '******' user = User( username=username, first_name=first_name, last_name=last_name, email=username + '@softseed.com', ) user.set_password('demo37') else: user = User( username='******' + str(num_completed), first_name=first_name, last_name=last_name, email='user' + str(num_completed) + '@softseed.com', ) user.set_password('user' + str(num_completed)) user.save() print('created: ', user.username, user.first_name, ' ', user.last_name) else: if watch:
def main(): user = User() user.guid = uuid4() # requests.post('http://google.com/?q=omg-some-really-long-annoying-string', header={'Content-type': 'application/json'}) pass
from orm.models import User, Address, Base from engine import engine from sqlalchemy.orm import Session from sqlalchemy.orm import aliased from sqlalchemy import func Base.metadata.create_all(bind=engine) session = Session(bind=engine) """ +-------------------------------------------------------------------------+ | 0. Adding some dummy data +-------------------------------------------------------------------------+ """ session.add_all([ User(name="ed", full_name="Ed Jones"), User(name="tyrion", full_name="Tyrion Lannister"), User(name="jon", full_name="Jon Snow"), ]) session.commit() """ +-------------------------------------------------------------------------+ | 1. querying use orm.query using an orm class +-------------------------------------------------------------------------+ """ query = session.query(User).filter(User.name == "tyrion").order_by(User.id) print(query.all()) """ +-------------------------------------------------------------------------+ | 2. querying specific columns +-------------------------------------------------------------------------+ """
from engine import engine """ +-------------------------------------------------------------------------+ | 1. Parent class for your ORM tables. Generally one base in an application. +-------------------------------------------------------------------------+ """ """ +-------------------------------------------------------------------------+ | 2. Declarative base when subclassed will create a 'model'. | The two key components are the table and mapper attribute. | Table - columns, constraints schema etc. | Mapper - mediates the relationships between the db table and the class. +-------------------------------------------------------------------------+ """ ed_user = User(name="ed", full_name="ed jones") print(ed_user) # create all tables which subclass Base Base.metadata.create_all(engine) from sqlalchemy.orm import Session session = Session(bind=engine) session.add(ed_user) print(session.new) """ +-------------------------------------------------------------------------+ | 3. Session will *flush* *pending* objects to the db before each query. +-------------------------------------------------------------------------+ """