def blog_id(id): if request.method == 'POST': comment_content = request.form['comment_content'] comment_name = request.form['comment_name'] comment = Comment(id=next_id(), blog_id=id, user_id='guest', user_name=comment_name, user_image='', content=comment_content, created_at=time.time()) comment.save() image = common.create_avatar_by_name(comment_name) user = User(id=next_id(), email='', passwd='', admin=0, name=comment_name, image=image, created_at=time.time()) mylog.info(image) # TODO 先使用name来进行判定是否唯一,后期希望能够使用email来判断是否唯一 _user = User.find_all('name= ?', [comment_name]) if len(_user) == 0: user.save() flash('comment and new user had been saved successfully!') blog = Blog.find(id) md_text = highlight.parse2markdown(blog.content) blog.html_content = md_text comments = Comment.find_all('blog_id= ?', [id]) return render_template('blogdetail.html', blog=blog, comments=comments)
def getValueOrDefault(self, key): value = getattr(self, key, None) if value is None: field = self.__mappings__[key] if field.default is not None: value = field.default() if callable(field.default) else field.default mylog.info("using default value for %s: %s" % (key, str(value))) setattr(self, key, value) return value
def issue_addComment(lst): issue = lst[0] url, headers = prepare('issue', '/{}/{}'.format(issue, 'comment')) data = json.dumps({"body": lst[1]}) f, r = send_request(url, method.Post, headers, None, data) if not f: return False, r mylog.info(r) return True, ['Comment(ID: ' + r['id'] + ')added']
def init_config(app): # 获取配置环境 change_environ() # 获取配置文件,并进行flask的相关配置 config = load_config() app.config.from_object(config) mylog.info('Debug mode is %s' % app.config['DEBUG']) return app.config['DEBUG']
def getValueOrDefault(self, key): value = getattr(self, key, None) if value is None: field = self.__mappings__[key] if field.default is not None: value = field.default() if callable( field.default) else field.default mylog.info('using default value for %s: %s' % (key, str(value))) setattr(self, key, value) return value
def archive(): # 获取年 years = Blog.find_all(groupby='year') # 根据‘year’获取不同年的blog数据 blogs = [] for year_blog in years: year = year_blog.year # 根据year获取该年的blogs blogs_year = Blog.find_all('year= ?', [year], orderBy='created_at desc') mylog.info(blogs_year) blogs.append(blogs_year) return render_template('archive.html', blogs=blogs)
def issue_assign(lst): issue = lst[0] assignee = lst[1] url, headers = prepare('issue', '/{}/assignee'.format(issue)) data = '{"name":"' + assignee + '"}' f, r = send_request(url, method.Put, headers, None, data) if not f: return False, r msg = '{} successfully assigned to {}'.format(issue, assignee) mylog.info(msg) return True, [msg]
def login(lst): un = lst[0] pw = lst[1] url = prepare('login')[0] headers = {'Content-Type': 'application/json'} data = json.dumps({"username": un, "password": pw}) try: r = requests.post( url, headers=headers, data=data, timeout=glob_dic.get_value('timeout'), verify=False) mylog.error(r.text) print('login here') if r.status_code == 401: mylog.error("401 Unauthorized") return False,['401 Unauthorized!','Please make sure the username and password are correct'] try: r.raise_for_status() except requests.exceptions.HTTPError as err: mylog.error(err) try: errmsg = r.json()['errorMessages'][0] mylog.error(errmsg) except KeyError: pass except json.decoder.JSONDecodeError: pass return ( False, ['Login failed! Please make sure that your username and password are correct!'] ) j = r.json() try: glob_dic.set_value( 'cookie', j['session']['name'] + '=' + j['session']['value']) except KeyError: mylog.error('No session information from HTTP response\r\n' + r.text) return (False, ['session info not found!']) f = open(glob_dic.get_value('cookie_path') + "cookie.txt", "w") f.write(glob_dic.get_value('cookie')) f.close() mylog.info("Successfully logged in as " + un) thr = Thread(target=download, args=(None, un)) thr.start() return (True, ["Success"]) except requests.exceptions.RequestException as err: mylog.error(err) return (False, ['Login failed due to an internet error!'])
def logout(): url, headers = prepare('logout') try: r = requests.delete(url, headers = headers, timeout=5) try: r.raise_for_status() except requests.exceptions.HTTPError: pass except requests.exceptions.RequestException: pass f = open(glob_dic.get_value('cookie_path') + "cookie.txt", "w") f.write('') f.close glob_dic.set_value('cookie', '') mylog.info('Successfully logged out') return (True, ['Successfully logged out'])
def issue_transit(lst): issue = lst[0] status = lst[1].title() url, headers = prepare( 'issue', '/{}/transitions?expand=transitions.fields'.format(issue)) data = {} dic = {} if not issue_get_tansition(issue, dic): return False, ['no transit is avaiable'] transition = {"id": dic.get(status)} data = json.dumps({"transition": transition}) f, r = send_request(url, method.Post, headers, None, data) if not f: return False, ['Error occured durin transit'] + r msg = 'Status of {} has been changed to {}'.format(issue, status) mylog.info(msg) return True, [msg]
def init_jinja2(config, **kw): mylog.info('init jinja2...') options = dict(autoescape=kw.get('autoescape', True), block_start_string=kw.get('block_start_string', '{%'), block_end_string=kw.get('block_end_string', '%}'), variable_start_string=kw.get('variable_start_string', '{{'), variable_end_string=kw.get('variable_end_string', '}}'), auto_reload=kw.get('auto_reload', True)) path = kw.get('path', None) if path is None: path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') mylog.info('set jinja2 template path: %s' % path) env = Environment(loader=FileSystemLoader(path), **options) filters = kw.get('filters', None) if filters is not None: for name, f in filters.items(): env.filters[name] = f config['__templating__'] = env
def issue_getComment(lst): issue = lst[0] url, headers = prepare('issue', '/{}{}'.format(issue, '/comment')) f, r = send_request(url, method.Get, headers, None, None) if not f: return False, r comments = r.get('comments', []) if len(comments) > 0: string = 'Here are the comments for ' + issue + ':\r\n' for com in comments: string += '"{}"\r\n\twrote by {}\r\n\t{}\r\n\t(cid: {})\r\n'.format( com['body'], com['updateAuthor']['key'], com['created'], com['id']) mylog.info(string) return False, [string] else: mylog.info('get empty msg') return True, ["There is no comment yet!"]
def init_jinja2(config, **kw): mylog.info('init jinja2...') options = dict( autoescape=kw.get('autoescape', True), block_start_string=kw.get('block_start_string', '{%'), block_end_string=kw.get('block_end_string', '%}'), variable_start_string=kw.get('variable_start_string', '{{'), variable_end_string=kw.get('variable_end_string', '}}'), auto_reload=kw.get('auto_reload', True) ) path = kw.get('path', None) if path is None: path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') mylog.info('set jinja2 template path: %s' % path) env = Environment(loader=FileSystemLoader(path), **options) filters = kw.get('filters', None) if filters is not None: for name, f in filters.items(): env.filters[name] = f config['__templating__'] = env
def issue_delComment(lst): issue = lst[0] cid = lst[1] url, headers = prepare('issue', '/{}{}{}'.format(issue, '/comment/', cid)) f, r = send_request(url, method.Delete, headers, None, None) if not f: return False, r mylog.info('Comment {} deleted'.format(cid)) return True, ['Comment deleted'] # login(['admin','admin']) # issue_create(['test', 'story','This is summaryyyyyyy', '', 'medium', '', 'This is Decriptionnnnnnn', 'ysg','test sprint 1']) # issue_assign(['TEST-38','hang']) # issue_assign(['TEST-29','hang']) # finduser('xp zheng') # finduser('yuhang4') # issue_addComment(['Test-77','New added comments']) # issue_delComment(['Test-77',10111]) # issue_getComment(['Test-77']) # issue_assign(['Test-01','testuser1']) # issue_transit(['TEST-72', 'Done'])
def send_request(url, method, headers, params, data): r = requests.Response try: if method is method.Get: r = requests.get(url, headers=headers, params=params, timeout=glob_dic.get_value('timeout'), verify=False) elif method is method.Put: r = requests.put(url, headers=headers, data=data, timeout=glob_dic.get_value('timeout'), verify=False) elif method is method.Delete: r = requests.delete(url, headers=headers, data=data, timeout=glob_dic.get_value('timeout'), verify=False) elif method is method.Post: r = requests.post(url, headers=headers, data=data, timeout=glob_dic.get_value('timeout'), verify=False) else: mylog.error('Wrong method that not suppord:' + str(method)) return (False, ['Unknown internal error occured']) if r.status_code == 401: mylog.error("401 Unauthorized") raise Super401() try: r.raise_for_status() except requests.exceptions.HTTPError as err: mylog.error(r.text) sLst = [ 'Request denied!', 'error code: {} {}'.format(str(r.status_code), str(_codes[r.status_code][0])) ] try: lst = r.json().get('errorMessages', []) for errors in lst: sLst.append(errors) dic = r.json().get('errors', {}) for key in dic: sLst.append('{} '.format(dic[key])) except json.JSONDecodeError: pass sLst.append('Please try again') return (False, sLst) mylog.info(r) try: try: s = '' lst = r.json()['warningMessages'] for errors in lst: s += errors + '\r\n' mylog.error(s) return (False, [s]) except KeyError: return (True, r.json()) except TypeError: return (True, r.json()) except json.JSONDecodeError: return (True, r) except requests.exceptions.RequestException as err: mylog.error(err) return (False, [ 'Internet error', 'Try:', '\tChecking the network cables, modem, and route', '\tReconnecting to Wi-Fi', '\tRunning Network Diagnostics' ])