def content(subject, title, username): res = studhelp_dbsql.get_post_contents(subject, title) content = res if content == -3: return error("") if content == ['This post does not exist']: return error("Script tags disabled temporarily") responses = studhelp_dbsql.get_post_responses(subject, title) if responses == -3: return error #if responses == ['Response does not exist']: # return [["",""]] print(responses) val = None for i in title: mod_i = ''.join(e for e in i if e.isalnum()) for char in mod_i.lower(): val = ord(char) - 96 return template("topic.tpl", title=title, unit=subject, content=content, responses=responses, server=conf.complete_server_conf(), username=username, value=val)
def new_comment(subject, title, comment, username): if len(comment) == 0: return error("Comment not written") ret = studhelp_dbsql.add_post_response(subject, title, comment, username) if ret == -3: return error("") return content(subject, title, username)
def new_message(sender, reciever, message): if len(message) == 0: return error("message not written") ret = studhelp_dbsql.add_message(sender, reciever, message) if ret == -3: return error() return get_messages(sender, reciever)
def new_post(subject, title, content, username): if len(title) == 0 or len(content) == 0: return error("Title and/or content not written") ret = studhelp_dbsql.add_new_post(username, subject, title, content) if ret == -3: return error("") url = conf.complete_server_conf() + '/homepage/' + subject redirect(url)
def reset_pass(email): if len(email) == 0: return error("No email mentioned") ret = studhelp_dbsql.send_password(email) url = conf.complete_server_conf() + "/" if ret == -3 or ret == -1: return error() return redirect(url)
def import_routes(route_location): # import route module_obj = None __import__(route_location, globals(), locals()) module_obj = sys.modules[route_location] url_properties = { 'urls' : ['GET', 'POST', 'PUT', 'DELETE'], 'gets' : ['GET'], 'posts': ['POST'], 'puts' : ['PUT'], 'deletes': ['DELETE'] } # urls for url_property in url_properties: methods = url_properties[url_property] if hasattr(module_obj, url_property): for url_pair in getattr(module_obj, url_property): # address route_address = url_pair[0] slashed_url = add_begining_slash(add_trailing_slash(route_address)) unslashed_url = add_begining_slash(remove_trailing_slash(route_address)) # callback if len(url_pair)==1: route_callback = 'Undefined callback' else: route_callback = url_pair[1] if isinstance(route_callback, str): content = route_callback def wrapper(): return content route_callback = wrapper # default values name, apply_, skip, configs = None, None, None, {} # name if len(url_pair)>2: name = url_pair[2] # apply if len(url_pair)>3: apply_ = url_pair[3] # skip if len(url_pair)>4: skip = url_pair[4] # configs if len(url_pair)>5: configs = url_pair[5] # call the routes route(slashed_url, methods, route_callback, name, apply_, skip, **configs) route(unslashed_url, methods, route_callback, name, apply_, skip, **configs) # hooks if hasattr(module_obj, 'hooks'): for hook_pair in module_obj.hooks: hook(hook_pair[0])(hook_pair[1]) # errors if hasattr(module_obj, 'errors'): for error_pair in module_obj.errors: error(error_pair[0])(error_pair[1])
def homepage(username): if len(username) == 0: return error() subject = studhelp_dbsql.get_user_subject(username) if subject == -3: return error() return template("homepage.tpl", name=username, subject=subject, server=conf.complete_server_conf())
def routeapp(obj): for kw in dir(obj): attr = getattr(obj, kw) if hasattr(attr, 'error'): bottle.error(attr.error)(attr) if hasattr(attr, 'delete'): bottle.delete(attr.delete)(attr) if hasattr(attr, 'put'): bottle.put(attr.put)(attr) if hasattr(attr, 'post'): bottle.post(attr.post)(attr) if hasattr(attr, 'route'): bottle.route(attr.route)(attr)
def wrapper(*args,**kwargs): try: try: uhmac = request.cookies.get('uhmac') token = request.cookies.get('token') uname = request.cookies.get('uname') hm = hmac.new(str(RSAKEY['passwd_store']),"UNHMAC_"+uname, hashlib.sha1) uhmac2 = hm.digest().encode('base64').strip() if not uhmac == uhmac2: raise AuthStatus.NotLoggedIn kn = redis_conf['prefix']+'#uSession' rtk = redis.hget(kn,uhmac) if rtk == None or rtk == "": raise AuthStatus.NotLoggedIn if not rtk == token: raise AuthStatus.NotLoggedIn except: SelfFailureLoggerModel.addlog(logging.DEBUG,'text/plain',"<DEBUG>[LoginError]%s"%traceback.format_exc()) raise AuthStatus.NotLoggedIn authobj = AuthObj() authobj.username = uname authobj.uhmac = uhmac kwargs ["auth"] = authobj try: result = func(*args,**kwargs) return result except: SelfFailureLoggerModel.addlog(logging.ERROR,'text/plain',traceback.format_exc()) return error(500) except AuthStatus.NotLoggedIn: SelfFailureLoggerModel.addlog(logging.DEBUG,'text/plain',"<DEBUG>[LoginFailure]%s"%traceback.format_exc()) return redirect("/login/",code=302)
def api_payssion_notify_url(): import hashlib p = ParamWarper(request) TRACE("REQ:", str(request.body)) pm_id, amount, currency, order_id, state = p.__pm_id, p.__amount, p.__currency, p.__order_id, p.__state # api_key|pm_id|amount|currency|order_id|state|sercret_key verify = '|'.join([ str(x) for x in [ PSS_APP_KEY, pm_id, amount, currency, order_id, state, PSS_SECRET_KEY ] ]) TRACE("BEFORE:", verify) verify = hashlib.md5(verify).hexdigest() TRACE("VERIFY:", verify) TRACE("SIGN:", p.__notify_sig) out_trade_no, transaction_id = order_id, p.__transaction_id if str(verify).lower() != str(p.__notify_sig).lower(): TRACE("PARAM", pm_id, amount, currency, order_id) return error(404) if p.__state == 'completed': with DB() as db: db.sql_exec( """ INSERT INTO poker.paycallback (TRANID, PAYID) VALUES ('%s', '%s'); """, transaction_id, out_trade_no) db.commit() return HTTPResponse("success", content_type="text/xml")
def getQuestion(questionTitle): try: questionData = db.getQuestion(questionTitle) except askExceptions.NotExist as e: return error(e) return template('question.tpl',questionData=questionData)
def parse_url(url): if get_status_code(url)==404: # page is not found return error(PageNotFoundError()) output = {} crawler = LinkedinCrawler() try: items = crawler.start(url) # launching crawler except BadFormatError: return error(BadFormatError()) output["tags"]= [elem.get('label') for elem in items if 'label' in elem.keys()]# formatting output output["educations"] = [elem for elem in items if 'school' in elem.keys()] return json.dumps(output)
def deleteAnswer(questionTitle): answerID = request.forms.get('answerID') try: db.delAnswer(questionTitle,answerID) except askExceptions.NotExist as e: return error(e) redirect("/question/"+questionTitle)
def parse(): url = request.GET.get('url') print "Request parameters: url=",url if not url: return error(PageNotFoundError()) return parse_url(url)
def api_wxpay_notify_url(): """微信回调""" wx = H5WXPlay() if not wx.verify_notify(request.body): return error(404) def to_xml(raw): s = "" for k, v in raw.items(): s += "<{0}>{1}</{0}>".format(k, v) s = "<xml>{0}</xml>".format(s) return s.encode("utf-8") r = wx.notify_xml_string_to_dict(request.body) out_trade_no = r['out_trade_no'] return_code = r['return_code'] transaction_id = r['transaction_id'] if return_code == 'SUCCESS': with DB() as db: db.sql_proc("sp_pay_notify", out_trade_no, transaction_id) db.commit() return HTTPResponse(to_xml( dict(return_code=r['return_code'], return_msg="OK")), content_type="text/xml")
def voteDown(questionTitle): answerID = request.forms.get("answerID") try: votes = db.voteDown(questionTitle, answerID) except askExceptions.NotExist as e: return error(e) redirect("/question/"+questionTitle)
def deleteComment(questionTitle): commentID = request.forms.get("commentID") answerID = request.forms.get('answerID') try: db.deleteComment(questionTitle,answerID,commentID) except askExceptions.NotExist as e: return error(e) redirect("/question/"+questionTitle)
def get_messages(username, chat_with): ret = studhelp_dbsql.view_chat_history(username, chat_with) if ret == -3: return error("") return template("chat.tpl", chat=ret, reciever=chat_with, server=conf.complete_server_conf())
def postAnswer(questionTitle): author = "" text = request.forms.get('text') try: db.addAnswer(questionTitle,text,author) except askExceptions.NotExist as e: return error(e) redirect("/question/"+questionTitle)
def show(item): dbname.execute( 'SELECT * from angelo.temperatura') # where sensorid="%s"', (item,)) row = dbname.fetchone() return row if row: return template('showitem', page=row) return error(404, "Page not found")
def updateAnswer(questionTitle): answerId = request.forms.get('answerID') text = request.forms.get('text') print "update"+str(text) try: db.updateAnswer(questionTitle,answerId,text) except askExceptions.NotExist as e: return error(e) redirect("/question/"+questionTitle)
def display_episode(showname, episodenum): sectionTemplate = "./templates/episode.tpl" sectionData = utils.displayEp(showname, episodenum) if sectionData == 'error': return error(error) return template("./pages/index.html", version=utils.getVersion(), sectionTemplate=sectionTemplate, sectionData={sectionData})
def updateComment(questionTitle): answerID = request.forms.get('answerID') commentID = request.forms.get("commentID") text = request.forms.get('text') try: db.updateComment(questionTitle,answerID,commentID,text) except askExceptions.NotExist as e: return error(e) redirect("/question/"+questionTitle)
def addUnit(unit, username): #ADD unit to DB with the username and return homepage subject = studhelp_dbsql.unit_add(username, unit) if subject == -3: return error() return template("homepage.tpl", name=username, subject=subject, server=conf.complete_server_conf())
def postComment(questionTitle): author = "" answerID = request.forms.get('answerID') text = request.forms.get('text') try: db.addComment(questionTitle,answerID,text,author) except askExceptions.NotExist as e: return error(e) redirect("/question/"+questionTitle)
def display_show(showname): sectionTemplate = "./templates/show.tpl" sectionData = utils.displayShow(showname) if sectionData == 'error': return error(error) return template("./pages/index.html", version=utils.getVersion(), sectionTemplate=sectionTemplate, sectionData=sectionData)
def add_twitter(): user = users.get_current_user() if user is None: redirect("/login?{0}".format( urllib.urlencode(dict(continue_url=request.url)))) else: session = request.environ.get('beaker.session') auth = session.get("twitter_auth") verifier = request.GET.get('oauth_verifier') if auth is not None and auth.request_token is None: auth = None twi = TwitterUser.get_by_key_name(user.email()) auth_url = '' if twi is None: #first if auth is None or verifier is None: auth = tweepy.OAuthHandler(consumer_key, consumer_secret, request.url) auth_url = auth.get_authorization_url() session["twitter_auth"] = auth session.save() redirect(auth_url) else: try: auth.get_access_token(verifier) except tweepy.TweepError: error('Error! Failed to get access token.') twi = TwitterUser.get_or_insert( user.email(), user=user, last_retweeted_id=0, twitter_access_token=auth.access_token.key, twitter_access_token_secret=auth.access_token.secret, twitter_id=auth.get_username()) session["twitter_auth"] = None session.save() redirect("/twitter")
def overview_messages(username): ret = studhelp_dbsql.view_messages(username) if ret == -3: return error("") users = [] users = get_users(ret, username) return template("view_all_messages.tpl", username=username, users=users, server=conf.complete_server_conf())
def import_routes(route_location): # import route module_obj = None __import__(route_location, globals(), locals()) module_obj = sys.modules[route_location] # urls if hasattr(module_obj, 'urls'): for url_pair in module_obj.urls: slashed_url = add_trailing_slash(url_pair[0]) unslashed_url = remove_trailing_slash(url_pair[0]) route(slashed_url)(url_pair[1]) route(unslashed_url)(url_pair[1]) # hooks if hasattr(module_obj, 'hooks'): for hook_pair in module_obj.hooks: hook(hook_pair[0])(hook_pair[1]) # errors if hasattr(module_obj, 'errors'): for error_pair in module_obj.errors: error(error_pair[0])(error_pair[1])
def listTopics(unit, username): title = studhelp_dbsql.get_all_post_title(unit) if title == -1: return error() url = 'homepage/' + unit return template("UnitDiscussion.tpl", title=title, url=url, unit=unit, server=conf.complete_server_conf(), username=username)
def login_check(username, password): if len(username) == 0: return error("No username written") if len(password) == 0: return error("No password written") result = studhelp_dbsql.check_login(username, password) if result == 0: #checking the units that the user chose and only showing them in the homepage subject = studhelp_dbsql.get_user_subject(username) if subject == -3: return error() response.set_cookie("username", username, secret='houdini+stockfish') return template("homepage.tpl", name=username, subject=subject, server=conf.complete_server_conf()) else: return template("LoginError.tpl", reason="check credentials", server=conf.complete_server_conf())
def signup_check(username, password, email): u_l = len(username) p_l = len(password) e_l = len(email) if u_l == 0 or p_l == 0 or e_l == 0: return error("One of the fields in the previous form was blank") result = studhelp_dbsql.check_signup(username, password) if (result == 0): studhelp_dbsql.add_user(username, password, email) return template("Login.tpl", server=conf.complete_server_conf()) else: return template("SignupError.tpl", server=conf.complete_server_conf())
def postNewQuestion(): print "body"+str(request.body) print "length:"+str(request.content_length) author = "" questionTitle = request.forms.get('title') text = request.forms.get('text') tags = request.forms.getlist('tags') print "questionTitle"+str(questionTitle) try: question = db.addNewQuestion(questionTitle,text,tags,author) redirect("/question/"+question.title) except askExceptions.NotExist as e: return error(e)
def api_aplipay_notify_url(): """支付宝回调""" TRACE("ALIPAYNOTIFY:=======") data = dict(request.POST) success = AliPay.verify_notify(data) if success: out_trade_no = data['out_trade_no'] trade_status = data["trade_status"] trade_no = data['trade_no'] if trade_status == 'TRADE_SUCCESS': with DB() as db: db.sql_proc("sp_pay_notify", out_trade_no, trade_no) db.commit() return HTTPResponse("success", content_type="text/xml") return error(404)
def test_error_routing(self): @bottle.route("/<code:int>") def throw_error(code): bottle.abort(code) # Decorator syntax @bottle.error(500) def catch_500(err): return err.status_line # Decorator syntax (unusual/custom error codes) @bottle.error(999) def catch_999(err): return err.status_line # Callback argument syntax def catch_404(err): return err.status_line bottle.error(404, callback=catch_404) self.assertBody("404 Not Found", '/not_found') self.assertBody("500 Internal Server Error", '/500') self.assertBody("999 Unknown", '/999')
def view(paper_name): paper_name = paper_name.strip('/') if paper_name not in paper_metadata: return bottle.error(404) template = jinja_env.get_template("view_paper.jinja2") render_cmd = "%s %s" % (notes_renderer, os.path.join( root_folder, paper_name, "notes." + notes_extension)) render_subproc = subprocess.Popen(render_cmd, shell=True, stdout=subprocess.PIPE) rendered_notes = render_subproc.communicate()[0].strip() return template.render(paper_info = paper_metadata[paper_name], paper_name = paper_name, rendered_notes = rendered_notes)
def mycard_notify_url(): p = ParamWarper(request) TRACE("MYCARDPARAM:", str(p.params)) data = p.__DATA TRACE(data) try: data = json.loads(data) ReturnCode = data['ReturnCode'] FacTradeSeq = data['FacTradeSeq'] TRACE("PARAM:", str(data)) if str(ReturnCode) == '1': for seq in FacTradeSeq: mycard_pay(seq) return HTTPResponse("success", content_type="text/xml") except Exception, e: TRACE_ERROR(e) return error(404)
def process_routes(routes): for config in routes: route(config["url"], method=config["method"])(config["controller"]) if production: error(404)(not_found) error(405)(not_allowed)
def deleteQuestion(questionTitle): try: db.deleteQuestion(questionTitle) except askExceptions.NotExist as e: return error(e) redirect("/")
def error404(error): return error(PageNotFoundError())
def icon_png(icon): response.set_header('Content-Type', 'image/png') try: return pkgutil.get_data('ejui', icon + '.png') except OSError: error(404)
def process_routes(routes): for config in routes: route(config["url"], method=config["method"])(config["controller"]) #comment the following two lines for debugging error(404)(not_found) error(405)(not_allowed)
def give_blob(job_id): return get_db()['jobs'][job_id]['blob'] @error(404)
def main(): error_codes = [404, 405, 503] for error_code in error_codes: bottle.error(error_code)(lambda error: _default_handler()) bottle.run(quiet=True)
# 'sub_title': data[0]['sub_title'], # 'thumbnail': data[0]['thumbnail'] # } # if data: # return json.dumps([ # 'meta': meta, # 'topic': data # ]) # else: # return json.dumps([ # 'topic': [], # 'meta': [] # ]) bottle.error(404) def error404(error): return json.dumps({ 'statusCode': 404, 'status': 'error', 'message': 'Not Found' }) bottle.error(500) def error500(error): return json.dumps({ 'statusCode': 500, 'status': 'error', 'message': 'Internal Server Error, our fat cat did something wrong' })
def display_episode(showname, episodenum): sectionData = utils.displayEp(showname, episodenum) if sectionData == 'error': return error(error) return template("./templates/episode.tpl", result=sectionData)
def display_show(showname): sectionData = utils.displayShow(showname) if sectionData == 'error': return error(error) return template("./templates/show.tpl", result=sectionData)