def add_entry(): _check_user() i = ctx.request.input(id='', title='', subtitle='', description='') title = i.title.strip() subtitle = i.subtitle.strip() description = i.description.strip() if not title: raise APIError('value', 'title', 'Title is empty') cv = get_default_cv(ctx.user.id) for s in cv.sections: if s.id == i.id: next_id = db.next_str() logging.info('NEXT-ID: ' + next_id) db.insert('entries', id=next_id, user_id=ctx.user.id, resume_id=cv.id, section_id=s.id, display_order=len(s.entries), title=title, subtitle=subtitle, description=description, picture='', version=0) return dict(id=next_id, title=title, subtitle=subtitle, description=description) raise APIError('value', 'id', 'Invalid section id.')
def register_user(): i = ctx.request.input(name='', email='', password='') name = i.name.strip() email = i.email.strip() password = i.password if not name: raise APIError('name') if not email or not _RE_EMAIL.match(email): raise APIError('email') if not password or not _RE_MD5.match(password): raise APIError('password') file = i.avatar if file: dirname = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'avatar') m = hashlib.md5() m.update(email) with open(dirname + '\\' + m.hexdigest() + '.jpg', 'wb') as f: f.write(file.file.read()) user = User(name=name, email=email, password=password, image=m.hexdigest()) else: user = User(name=name, email=email, password=password) session.add(user) session.commit() cookie = make_signed_cookie(user.id, user.password, None) ctx.response.set_cookie(_COOKIE_NAME, cookie.encode('utf-8')) # 恩,框架只对body进行编码,头部转码 return user.as_dict()
def create_blog(): if not ctx.request.user: raise HttpError.seeother('/login') if not ctx.request.manager: raise APIError('not admin') i = ctx.request.input(name='', summary='', content='', blogid='', currentcat='') name = i.name summary = i.summary content = i.content currentcat = i.currentcat if not name: raise APIError('name cant be none') if not summary: raise APIError('summary cant be none') if not content: raise APIError('content cant be none') if i.blogid: # blog = select_one('select * from blogs where id=?', i.blogid) # blog_to_update = Blog(id=blog.id, name=name, summary=summary, content=content) # blog_to_update.update() session.query(Blog).filter(Blog.id == i.blogid).\ update({'name': name, 'summary': summary, 'content': content, 'category':currentcat}) session.commit() # return translate_time(select_one('select * from blogs where id=?', i.blogid)) return translate_time(session.query(Blog).filter(Blog.id == i.blogid).first()) # blog = Blog(name=name, summary=summary, content=content,user_id=ctx.request.user.id, user_name=ctx.request.user.name ) # blog.insert() blog = Blog(name=name, summary=summary, content=content, user=ctx.request.user.id, category=currentcat) session.add(blog) session.commit() return blog.as_dict()
def do_register(): i = ctx.request.input(name='', email='', passwd='') name = i.name.strip() if not name: raise APIError('value', '', 'Invalid name.') email = i.email.strip().lower() check_email(email) passwd = i.passwd check_md5_passwd(passwd) us = db.select('select * from users where email=?', email) if us: raise APIError('register', '', 'Email already registered.') uid = db.next_str() db.insert('users', id=uid, name=name, email=email, passwd=passwd, version=0) make_session_cookie(uid, passwd) return {'id': uid}
def add_section(): _check_user() i = ctx.request.input(kind='', title='', description='') kind = i.kind if not kind in _SECTIONS_SET: raise APIError('value', 'kind', 'Invalid kind.') title = i.title.strip() if not title: title = _SECTIONS_DICT.get(kind) description = i.description.strip() cv = get_default_cv(ctx.user.id) for s in cv.sections: if s.kind == kind: raise APIError('value', '', 'Section exist.') next_id = db.next_str() db.insert('sections', id=next_id, user_id=ctx.user.id, resume_id=cv.id, display_order=len(cv.sections), kind=kind, title=title, description=description, version=0) return dict(id=next_id, kind=kind, title=title, description=description)
def validate_analyzers(self, asset_type, analyzers): """ Validate the given list of analyzers (if valid the analyzers are returned. """ # Check the structure of the analyzers is valid if not isinstance(analyzers, list): raise APIError( 'invalid_request', hint='Request body JSON must be a list.' ) if len(analyzers) == 0: raise APIError( 'invalid_request', hint='At least one analyzer is required.' ) # Check each analyzer is valid for analyzer in analyzers: # Check structure if not ( len(analyzer) == 2 and isinstance(analyzer[0], str) and isinstance(analyzer[1], dict) ): raise APIError( 'invalid_request', hint=f'Invalid analyzer structure: {analyzer}' ) # Check the analyzer exists analyzer_cls = get_analyzer(asset_type, analyzer[0]) if not analyzer_cls: raise APIError( 'invalid_request', hint=f'Unknown analyzer: {asset_type}:{analyzer[0]}.' ) # Check the settings for the analyzer are correct settings_form = analyzer_cls.get_settings_form_cls()( MultiDict({ k: v for k, v in analyzer[1].items() if v is not None }) ) if not settings_form.validate(): raise APIError( 'invalid_request', hint=( 'Invalid settings for analyzer: ' f'{asset_type}:{analyzer[0]}.' ), arg_errors=settings_form.errors ) return analyzers
def delete_course(id): if 'role' not in session or not session['role'] == 'admin': raise APIError('Insufficient permission', status_code=403) course = Course.query.filter(Course.id == id).first() if not course: raise APIError('未找到指定的课程', status_code=404) db.session.delete(course) db.session.commit() return {'impact': 1}
def write_rating(selection_id, rating): sel = Selection.query.filter(Selection.id == int(selection_id)).first() if not sel: raise APIError('未找到相应的选课信息', status_code=404) try: sel.rating = float(rating) db.session.commit() except ValueError: raise APIError('请输入数字', status_code=500) return sel.dict
def update_resume(): _check_user() i = ctx.request.input(id='', title='') if not i.id: raise APIError('value', 'id', 'id is empty.') title = i.title.strip() if not title: raise APIError('value', 'title', 'title is empty') cv = get_default_cv(ctx.user.id) _check_user_id(cv.user_id) db.update('update resumes set title=?, version=version+1 where id=?', title, cv.id) return dict(result=True)
def update_course(id, fields): if 'role' not in session or not session['role'] == 'admin': raise APIError('Insufficient permission', status_code=403) course = Course.query.filter(Course.id == id).first() if not course: raise APIError('未找到指定的课程', status_code=404) for key, value in fields.items(): course.__setattr__(key, value) db.session.commit() return course.dict
def query_user_by_numid(role, id, dict=True): if role.lower() == 'student': user = Student.query.filter(Student.id == int(id)).first() elif role.lower() == 'teacher': user = Teacher.query.filter(Teacher.id == int(id)).first() elif role.lower() == 'admin': user = Admin.query.filter(Admin.id == int(id)).first() else: raise APIError('Invalid role') if not user: raise APIError('用户不存在', status_code=404) return user.dict if dict else user
def login(username, password, role): if username == '' or password == '' or role == '': raise APIError('请输入用户名,密码和登陆角色', status_code=400) userobj = query_user_by_cred(role, username, hash_password(password)) if not userobj: raise APIError('请输入正确的用户名,密码与登陆角色', status_code=400) session['role'] = role creds = extract_user_credential(userobj) for k, v in creds.items(): session[k] = v return userobj.dict
def raw_query_threat_recon_attribution(indicator, api_key): """ Uses an indicator and the api key to query the threat recon database. Returns a list of python dicts corresponding to the JSON output from the server (results only). If no results, returns an empty list. Will throw APIError exception if the ResponseCode < 0. """ # NOTE: results will have mixed-case keys. In general, these # should not be used directly - the TRIndicator objects use # lower-case attributes (and generate dicts with lower-case keys). params = urllib.urlencode({'api_key': api_key, 'attribution': indicator}) urllib2.install_opener(urllib2.build_opener(HTTPSHandlerV3())) f = urllib2.urlopen("https://api.threatrecon.co/api/v1/search/attribution", params) data = json.load(f) response = data.get("ResponseCode", -99) if response < 0: raise APIError(response) results = data.get("Results", []) lowerresults = [] if results: # can be None, so make sure to check for r in results: lowerresults.append({k.lower(): v for k, v in r.items()}) return lowerresults
def write_grade(record_id, regular, midterm, final, total): sel = Selection.query.filter(Selection.id == record_id).first() if not sel: raise APIError('未找到相应的选课信息', status_code=404) try: sel.regular = int(regular) sel.mid_term = int(midterm) sel.final = int(final) sel.total = int(total) sel.GPA = compute_gpa(int(total)) db.session.commit() except ValueError: raise APIError('请输入整数', status_code=500) return sel.dict
def deleteblog(): if ctx.request.user and ctx.request.manager: i = ctx.request.input() blogid = i.blogid session.query(Blog).filter(Blog.id == blogid).delete() session.commit() return blog.as_dict() raise APIError('not admin')
def update_section(): _check_user() i = ctx.request.input(id='', title='', description='') if not i.id: raise APIError('value', 'id', 'id is empty.') title = i.title.strip() description = i.description.strip() if not title: raise APIError('value', 'title', 'title is empty') section = db.select_one('select * from sections where id=?', i.id) _check_user_id(section.user_id) db.update( 'update sections set title=?, description=?, version=version+1 where id=?', title, description, section.id) db.update('update resumes set version=version+1 where id=?', section.resume_id) return dict(result=True)
def remove_selection(id): sel = Selection.query.filter(Selection.id == int(id)).first() if not sel: raise APIError('未找到指定选课信息', status_code=404) db.session.delete(sel) db.session.commit() return {"impact": 1}
def postcomments(blogid): user = ctx.request.user content = ctx.request.input().newcomment if user and content.strip(): comment = Comment(blog=blogid, user=user.id, content=content) session.add(comment) session.commit() return translate_time(comment.as_dict()) raise APIError('not user or blank content')
def update_selection(id, student, course): sel = Selection.query.filter(Selection.id == int(id)).first() if not sel: raise APIError('未找到指定的选课信息', status_code=404) sel.student = int(student) sel.course = int(course) db.session.commit() return sel
def get_variation(self, asset, name): """ Return the named variation from the asset and raise an error if the variation does not exists. """ variation = asset.variations.get(name) if not variation: raise APIError('not_found', hint=f'Variation not found: {name}') return variation
def add_course(fields): if 'role' not in session or not session['role'] == 'admin': raise APIError('Insufficient permission', status_code=403) course = Course() for key, value in fields.items(): course.__setattr__(key, value) db.session.add(course) db.session.commit() return course.dict
def do_signin(): i = ctx.request.input(email='', passwd='', remember='') email = i.email.strip().lower() passwd = i.passwd if not email: raise APIError('auth:failed', '', 'Bad email or password.') if not passwd: raise APIError('auth:failed', '', 'Bad email or password.') us = db.select('select * from users where email=?', email) if not us: raise APIError('auth:failed', '', 'Bad email or password.') u = us[0] if passwd != u.passwd: raise APIError('auth:failed', '', 'Bad email or password.') expires = None if i.remember: expires = time.time() + _SESSION_COOKIE_EXPIRES make_session_cookie(u.id, passwd, expires) # clear passwd: u.passwd = '******' return dict(redirect='/cv/%s' % u.id)
def get(self): # Validate the arguments form = ManyForm(to_multi_dict(self.request.query_arguments)) if not form.validate(): raise APIError( 'invalid_request', arg_errors=form.errors ) form_data = form.data # Build the document query query_stack = [Q.account == self.account] if form_data['q']: q = form_data['q'] q_match = re.compile(re.escape(remove_accents(q)), re.I) query_stack.append(Q.name == q_match) if form_data['backend'] == 'public': query_stack.append(Q.secure == True) if form_data['backend'] == 'secure': query_stack.append(Q.secure == False) if form_data['type']: query_stack.append(Q.type == form_data['type']) # Get the paginated results response = paginate( Asset, query_stack, self.request, before=form_data['before'], after=form_data['after'], limit=form_data['limit'], projection={ 'created': True, 'modified': True, 'name': True, 'secure': True, 'type': True, 'uid': True, 'ext': True } ) self.write(response)
def list_user(role, search): page = int(get_arg(search, 'page', 1)) limit = int(get_arg(search, 'limit', 10)) id_keyword = get_arg(search, 'keyword', '') if role == 'student': query = Student.query.filter(or_(Student.sid.like('%%%s%%' % id_keyword), Student.name.like('%%%s%%' % id_keyword))) elif role == 'teacher': query = Teacher.query.filter(or_(Teacher.tid.like('%%%s%%' % id_keyword), Teacher.name.like('%%%s%%' % id_keyword))) elif role == 'admin': query = Admin.query.filter(Admin.username.like('%%%s%%' % id_keyword)) else: raise APIError('Invalid role') users = query.offset(limit * (page - 1)).limit(limit).all() return [user.dict for user in users]
def create_selection(student_id, course_id): student = query_user_by_numid('student', student_id) course = query_course_by_id(course_id) if not course: raise APIError(u'课程不存在', status_code=404) sel = Selection() sel.student = int(student_id) sel.course = int(course_id) sel.term = '' db.session.add(sel) db.session.commit() return sel.dict
def post(self): """ Removes any existing timeout for one or more existing assets making the assets persistent. Set a timeout for one or more assets. After the timeout has expired the assets will be automatically deleted. NOTE: The files associated with expired assets are delete periodically and therefore may still temporarily be available after the asset has expired and is not longer available via the API. """ assets = self.get_assets(projection={'uid': True}) # Validate the arguments form = ExpireForm(to_multi_dict(self.request.body_arguments)) if not form.validate(): raise APIError( 'invalid_request', arg_errors=form.errors ) form_data = form.data # Update the expires timestamp for the asset expires = time.time() + form_data['seconds'] Asset.get_collection().update( In(Q._id, [a._id for a in assets]).to_dict(), { '$set': { 'expires': time.time() + form_data['seconds'], 'modified': datetime.utcnow() } }, multi=True ) self.write({ 'results': [ { 'uid': a.uid, 'expires': expires } for a in assets ] })
def get_asset(self, uid, projection=None): """ Get the asset for the given `uid` and raise an error if no asset is found. """ assert not projection or 'expires' in projection, \ '`expires` must be included by the projection' # Fetch the asset asset = Asset.one(And(Q.account == self.account, Q.uid == uid), projection=(projection or self.DEFAULT_PROJECTION)) if not asset or asset.expired: raise APIError('not_found', hint=f'Asset not found for uid: {uid}.') return asset
def delete_entry(): _check_user() i = ctx.request.input(id='') if not i.id: raise APIError('value', 'id', 'id is empty.') entry = db.select_one('select * from entries where id=?', i.id) _check_user_id(entry.user_id) entries = db.select( 'select * from entries where section_id=? order by display_order', entry.section_id) display_ids = [en.id for en in entries if en.id != i.id] db.update('delete from entries where id=?', i.id) n = 0 for i in display_ids: db.update('update entries set display_order=? where id=?', n, i) db.update('update sections set version=version+1 where id=?', entry.section_id) return dict(result=True)
def admin_add_user(role, fields): if role.lower() == 'student': user = Student() elif role.lower() == 'teacher': user = Teacher() elif role.lower() == 'admin': user = Admin() else: raise APIError('Invalid role') fields['password'] = hash_password(fields['password']) for key, value in fields.items(): if not value: continue user.__setattr__(key, value) db.session.add(user) db.session.commit() return user.dict
def delete_section(): _check_user() i = ctx.request.input(id='') if not i.id: raise APIError('value', 'id', 'id is empty.') section = db.select_one('select * from sections where id=?', i.id) _check_user_id(section.user_id) cv = get_default_cv(ctx.user.id) sections = db.select( 'select * from sections where resume_id=? order by display_order', cv.id) display_ids = [s.id for s in sections if s.id != i.id] db.update('delete from entries where section_id=?', i.id) db.update('delete from sections where id=?', i.id) n = 0 for i in display_ids: db.update('update sections set display_order=? where id=?', n, i) db.update('update resumes set version=version+1 where id=?', cv.id) return dict(result=True)