def _store_files(kind, name, files): ''' Store a group of files as attachment. Args: kind: attachment type. e.g. 'image/cover' name: attachment name. files: list of (mime, meta, data). Returns: Attachments object. ''' ref_id = db.next_id() atta = Attachments(_id=ref_id, user_id=ctx.user._id, kind=kind, name=name) resources = [] for mime, meta, data in files: r_id = db.next_id() url = '/files/%s/%s' % (datetime.now().strftime('%Y/%m/%d'), r_id) r = Resources(_id=r_id, ref_id=ref_id, url=url, size=len(data), mime=mime, meta=meta, data=data) resources.append(r) atta.size = resources[0].size atta.resource_ids = ','.join([r._id for r in resources]) with db.transaction(): atta.insert() for r in resources: r.insert() return atta
def get_file(): logging.info('get file') user = ctx.request.user if not user: raise APIError('Authencation:fail','token','token is wrong','-1') i = ctx.request.input(filetype='.jpg') logging.info('the file is %s'% (i.file)) if not isinstance(i.file, MultipartFile): raise APIError('IO:error','file','read the file error','-1') logging.info('the token is %s' % i.token) file_name = next_id()+'.'+i.filetype file_path = os.path.join(image_path, file_name) logging.info('the out file is %s' % file_path) fw = open(file_path, 'wb') buf = i.file.file.readline() while buf != '': fw.write(buf) buf = i.file.file.readline() fw.close() image = Image(image_path=image_path_relative+file_name,user_id=user.id) image.insert() image.pop('image_path') image.errcode='0' return image
def api_create_article(): i = ctx.request.input(name='', summary='', category_id='', tags='', draft='', publish_time='', cover=None, content='') if not i.cover: raise APIValueError('cover', 'Cover cannot be empty.') name = assert_not_empty(i.name, 'name') summary = assert_not_empty(i.summary, 'summary') category_id = _check_category_id(i.category_id) content = assert_not_empty(i.content, 'content') draft = i.draft.lower()=='true' if draft: publish_time = time.time() + TIME_FEATURE else: publish_time = time2timestamp(i.publish_time) if i.publish_time else time.time() f = i.cover atta = uploaders.upload_cover(name, f.file.read()) article_id = db.next_id() article = Articles( \ _id = article_id, \ user_id = ctx.user._id, \ cover_id = atta._id, \ category_id = category_id, \ content_id = texts.set(article_id, content), \ publish_time = publish_time, \ draft = draft, \ user_name = ctx.user.name, \ name = name, \ summary = summary, \ tags = texts.format_tags(i.tags) \ ).insert() return dict(_id=article._id)
def create_user(): i = ctx.request.input(phone='',password='',code='') phone = i.phone.strip() password = i.password.strip() code = i.code.strip() verify = VerifyCode.find_first('where num=?', phone) logging.info('the code %s and verify %s' %(code,verify)) if not verify or verify.code!=code: raise APIError('register:failed','verify code','verify code is not correct.','-1') if time.time() - verify.created_at > 90: raise APIValueError('code',errcode='-3') if not phone or not _RE_PHONE.match(phone): raise APIValueError('phone',errcode='-1') if not password: raise APIValueError('password', errcode='-1') verify.delete() user = User.find_first('where phone=?',phone) if user and user.valid==True: raise APIError('register:failed','phone','phone is already in use.') if user: token = Token.find_first('where id=?', user.id) if not token: token_string = next_id() token = Token(id = user.id, token1=token_string, token2 = token_string) token.insert() else: token.token1 = next_id() logging.info('the update token is %s' % token.token1) token.update() user.password = password user.update() user.token = token.token1 else: user = User(phone=phone, valid=False, password=password) user.insert() token_string = next_id() token = Token(id = user.id, token1=token_string, token2 = token_string) token.insert() user.token = token.token1 user.pop('id') user.pop('password') user.pop('created_at') user.errcode='0' return user
def api_create_navigation(): i = ctx.request.input(name='', url='') name = assert_not_empty(i.name, 'name') url = assert_not_empty(i.url, 'url') max_display = db.select_one('select max(display_order) as max from navigations').max nav = Navigations(_id=db.next_id(), name=name, url=url, display_order=max_display+1).insert() _clear_navigations_cache() return nav
class Comment(Model): __table__ = 'comments' id = StringField(primary_key=True, default=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(50)') content = TextField() created_at = FloatField(updatable=False, default=time.time)
class User(Model): __table__ = 'users' id = StringField(primary_key=True, default=next_id(), ddl='varchar(50') email = StringField(updatable=False, ddl='varchar(50)') password = StringField(ddl='varchar(50)') admin = BooleanField() name = StringField(ddl='varchar(50)') image = StringField(ddl='varchar(50)') created_at = FtringField(updatable=False, default=time.time)
class Blog(Model): __table__ = 'blogs' id = StringField(primary_key=True, default=next_id(), ddl='varchar(50)') user_id = StringField(updatable=False, ddl='varchar(50)') user_name = StringField(ddl='varchar(50)') user_image = StringField(ddl='varchar(500)') name = StringField(ddl='varchar(50)') summary = StringField(ddl='varchar(200)') content = TextField() created_at = FloatField(updatable=False, default=time.time())
def api_create_navigation(): i = ctx.request.input(name='', url='') name = assert_not_empty(i.name, 'name') url = assert_not_empty(i.url, 'url') max_display = db.select_one( 'select max(display_order) as max from navigations').max nav = Navigations(_id=db.next_id(), name=name, url=url, display_order=max_display + 1).insert() _clear_navigations_cache() return nav
def api_create_page(): i = ctx.request.input(alias='', name='', tags='', draft='', content='') alias = assert_not_empty(i.alias, 'alias').lower() if _RE_ALIAS.match(alias) is None: raise APIValueError('alias', 'Invalid alias.') if Pages.select_one('where alias=?', alias): raise APIValueError('alias', 'Alias already exist.') name = assert_not_empty(i.name, 'name') content = assert_not_empty(i.content, 'content') draft = i.draft.lower() == 'true' page_id = db.next_id() page = Pages( \ _id = page_id, \ alias = alias, \ content_id = texts.set(page_id, content), \ draft = draft, \ name = name, \ tags = texts.format_tags(i.tags) \ ).insert() return dict(_id=page._id)
def api_create_article(): i = ctx.request.input(name='', summary='', category_id='', tags='', draft='', publish_time='', cover=None, content='') if not i.cover: raise APIValueError('cover', 'Cover cannot be empty.') name = assert_not_empty(i.name, 'name') summary = assert_not_empty(i.summary, 'summary') category_id = _check_category_id(i.category_id) content = assert_not_empty(i.content, 'content') draft = i.draft.lower() == 'true' if draft: publish_time = time.time() + TIME_FEATURE else: publish_time = time2timestamp( i.publish_time) if i.publish_time else time.time() f = i.cover atta = uploaders.upload_cover(name, f.file.read()) article_id = db.next_id() article = Articles( \ _id = article_id, \ user_id = ctx.user._id, \ cover_id = atta._id, \ category_id = category_id, \ content_id = texts.set(article_id, content), \ publish_time = publish_time, \ draft = draft, \ user_name = ctx.user.name, \ name = name, \ summary = summary, \ tags = texts.format_tags(i.tags) \ ).insert() return dict(_id=article._id)
def auth_callback_weibo(): provider = 'SinaWeibo' p = sns.create_client(provider) redirect = _get_redirect(excludes='/auth/') callback = 'http://%s/auth/callback/%s' % (ctx.request.host, provider) i = ctx.request.input(code='', state='') code = i.code if not code: raise IOError('missing code') state = i.state r = p.request_access_token(code, callback) thirdpart_id = r['uid'] auth_id = '%s-%s' % (provider, thirdpart_id) auth_token = r['access_token'] expires = r['expires'] user = None auser = AuthUsers.select_one('where auth_id=?', auth_id) if auser: # already signed in before: auser.auth_token = auth_token auser.expires = expires auser.update() user = Users.get_by_id(auser.user_id) make_session_cookie(provider, auser._id, auth_token, expires) else: # not signed in before, so try to get info: info = p.users.show.get(uid=thirdpart_id) user_id = db.next_id() email = info['email'] if 'email' in info else '%s@tmp' % user_id name = info['screen_name'] image_url = info['profile_image_url'] user = Users(_id=user_id, role=ROLE_GUEST, binds=provider, email=email, name=name, image_url=image_url, passwd='') auser = AuthUsers( \ user_id = user_id, \ auth_id = auth_id, \ auth_provider = provider, \ auth_token = auth_token, \ expires_time = expires \ ) with db.transaction(): user.insert() auser.insert() make_session_cookie(provider, auser._id, auth_token, expires) jscallback = ctx.request.get('jscallback', '') if jscallback: ctx.response.write( r'''<html><body><script> window.opener.%s({'id': '%s', 'name': '%s', 'image_url': '%s'}); self.close(); </script></body></html>''' % (jscallback, user._id, user.name.replace('\'', '\\\'').replace( '\n', '').replace('\r', ''), user.image_url)) return raise seeother('/')