repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
bukun/TorCMS
torcms/handlers/post_ajax_handler.py
PostAjaxHandler.p_recent
def p_recent(self, kind, cur_p='', with_catalog=True, with_date=True): ''' List posts that recent edited, partially. ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MPost.total_number(kind) / CMS_CFG['list_num']) kwd = { 'pager': '', 'title': 'Recent posts.', 'with_catalog': with_catalog, 'with_date': with_date, 'kind': kind, 'current_page': current_page_number, 'post_count': MPost.get_counts(), 'router': config.router_post[kind], } self.render('admin/post_ajax/post_list.html', kwd=kwd, view=MPost.query_recent(num=20, kind=kind), infos=MPost.query_pager_by_slug( kind=kind, current_page_num=current_page_number ), format_date=tools.format_date, userinfo=self.userinfo, cfg=CMS_CFG, )
python
def p_recent(self, kind, cur_p='', with_catalog=True, with_date=True): ''' List posts that recent edited, partially. ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MPost.total_number(kind) / CMS_CFG['list_num']) kwd = { 'pager': '', 'title': 'Recent posts.', 'with_catalog': with_catalog, 'with_date': with_date, 'kind': kind, 'current_page': current_page_number, 'post_count': MPost.get_counts(), 'router': config.router_post[kind], } self.render('admin/post_ajax/post_list.html', kwd=kwd, view=MPost.query_recent(num=20, kind=kind), infos=MPost.query_pager_by_slug( kind=kind, current_page_num=current_page_number ), format_date=tools.format_date, userinfo=self.userinfo, cfg=CMS_CFG, )
List posts that recent edited, partially.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_ajax_handler.py#L68-L99
bukun/TorCMS
torcms/handlers/post_ajax_handler.py
PostAjaxHandler.j_delete
def j_delete(self, *args): ''' Delete the post, but return the JSON. ''' uid = args[0] current_infor = MPost.get_by_uid(uid) tslug = MCategory.get_by_uid(current_infor.extinfo['def_cat_uid']) is_deleted = MPost.delete(uid) MCategory.update_count(current_infor.extinfo['def_cat_uid']) if is_deleted: output = { 'del_info': 1, 'cat_slug': tslug.slug, 'cat_id': tslug.uid, 'kind': current_infor.kind } else: output = { 'del_info': 0, } return json.dump(output, self)
python
def j_delete(self, *args): ''' Delete the post, but return the JSON. ''' uid = args[0] current_infor = MPost.get_by_uid(uid) tslug = MCategory.get_by_uid(current_infor.extinfo['def_cat_uid']) is_deleted = MPost.delete(uid) MCategory.update_count(current_infor.extinfo['def_cat_uid']) if is_deleted: output = { 'del_info': 1, 'cat_slug': tslug.slug, 'cat_id': tslug.uid, 'kind': current_infor.kind } else: output = { 'del_info': 0, } return json.dump(output, self)
Delete the post, but return the JSON.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_ajax_handler.py#L103-L126
bukun/TorCMS
torcms/script/script_init_tabels.py
run_init_tables
def run_init_tables(*args): ''' Run to init tables. ''' print('--') create_table(TabPost) create_table(TabTag) create_table(TabMember) create_table(TabWiki) create_table(TabLink) create_table(TabEntity) create_table(TabPostHist) create_table(TabWikiHist) create_table(TabCollect) create_table(TabPost2Tag) create_table(TabRel) create_table(TabEvaluation) create_table(TabUsage) create_table(TabReply) create_table(TabUser2Reply) create_table(TabRating) create_table(TabEntity2User) create_table(TabLog)
python
def run_init_tables(*args): ''' Run to init tables. ''' print('--') create_table(TabPost) create_table(TabTag) create_table(TabMember) create_table(TabWiki) create_table(TabLink) create_table(TabEntity) create_table(TabPostHist) create_table(TabWikiHist) create_table(TabCollect) create_table(TabPost2Tag) create_table(TabRel) create_table(TabEvaluation) create_table(TabUsage) create_table(TabReply) create_table(TabUser2Reply) create_table(TabRating) create_table(TabEntity2User) create_table(TabLog)
Run to init tables.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_init_tabels.py#L22-L45
bukun/TorCMS
torcms/handlers/entity2user_handler.py
Entity2UserHandler.all_list
def all_list(self, cur_p=''): ''' List the entities of the user. ''' # ToDo: 代码与 entity_handler 中 list 方法有重复 current_page_number = int(cur_p) if cur_p else 1 current_page_number = 1 if current_page_number < 1 else current_page_number kwd = { 'current_page': current_page_number } recs = MEntity2User.get_all_pager(current_page_num=current_page_number).objects() self.render('misc/entity/entity_download.html', imgs=recs, cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
python
def all_list(self, cur_p=''): ''' List the entities of the user. ''' # ToDo: 代码与 entity_handler 中 list 方法有重复 current_page_number = int(cur_p) if cur_p else 1 current_page_number = 1 if current_page_number < 1 else current_page_number kwd = { 'current_page': current_page_number } recs = MEntity2User.get_all_pager(current_page_num=current_page_number).objects() self.render('misc/entity/entity_download.html', imgs=recs, cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
List the entities of the user.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/entity2user_handler.py#L32-L49
bukun/TorCMS
torcms/handlers/entity2user_handler.py
Entity2UserHandler.user_list
def user_list(self, userid, cur_p=''): ''' List the entities of the user. ''' current_page_number = int(cur_p) if cur_p else 1 current_page_number = 1 if current_page_number < 1 else current_page_number kwd = { 'current_page': current_page_number } recs = MEntity2User.get_all_pager_by_username(userid, current_page_num=current_page_number).objects() self.render('misc/entity/entity_user_download.html', imgs=recs, cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
python
def user_list(self, userid, cur_p=''): ''' List the entities of the user. ''' current_page_number = int(cur_p) if cur_p else 1 current_page_number = 1 if current_page_number < 1 else current_page_number kwd = { 'current_page': current_page_number } recs = MEntity2User.get_all_pager_by_username(userid, current_page_num=current_page_number).objects() self.render('misc/entity/entity_user_download.html', imgs=recs, cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
List the entities of the user.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/entity2user_handler.py#L52-L69
bukun/TorCMS
torcms/core/tool/run_whoosh.py
gen_whoosh_database
def gen_whoosh_database(kind_arr, post_type): ''' kind_arr, define the `type` except Post, Page, Wiki post_type, define the templates for different kind. ''' SITE_CFG['LANG'] = SITE_CFG.get('LANG', 'zh') # Using jieba lib for Chinese. if SITE_CFG['LANG'] == 'zh' and ChineseAnalyzer: schema = Schema(title=TEXT(stored=True, analyzer=ChineseAnalyzer()), catid=TEXT(stored=True), type=TEXT(stored=True), link=ID(unique=True, stored=True), content=TEXT(stored=True, analyzer=ChineseAnalyzer())) else: schema = Schema(title=TEXT(stored=True, analyzer=StemmingAnalyzer()), catid=TEXT(stored=True), type=TEXT(stored=True), link=ID(unique=True, stored=True), content=TEXT(stored=True, analyzer=StemmingAnalyzer())) whoosh_db = 'database/whoosh' if os.path.exists(whoosh_db): create_idx = open_dir(whoosh_db) else: os.makedirs(whoosh_db) create_idx = create_in(whoosh_db, schema) writer = create_idx.writer() for switch in [True, False]: do_for_post(writer, rand=switch, doc_type=post_type['1']) do_for_wiki(writer, rand=switch, doc_type=post_type['1']) do_for_page(writer, rand=switch, doc_type=post_type['1']) for kind in kind_arr: do_for_app(writer, rand=switch, kind=kind, doc_type=post_type) writer.commit()
python
def gen_whoosh_database(kind_arr, post_type): ''' kind_arr, define the `type` except Post, Page, Wiki post_type, define the templates for different kind. ''' SITE_CFG['LANG'] = SITE_CFG.get('LANG', 'zh') # Using jieba lib for Chinese. if SITE_CFG['LANG'] == 'zh' and ChineseAnalyzer: schema = Schema(title=TEXT(stored=True, analyzer=ChineseAnalyzer()), catid=TEXT(stored=True), type=TEXT(stored=True), link=ID(unique=True, stored=True), content=TEXT(stored=True, analyzer=ChineseAnalyzer())) else: schema = Schema(title=TEXT(stored=True, analyzer=StemmingAnalyzer()), catid=TEXT(stored=True), type=TEXT(stored=True), link=ID(unique=True, stored=True), content=TEXT(stored=True, analyzer=StemmingAnalyzer())) whoosh_db = 'database/whoosh' if os.path.exists(whoosh_db): create_idx = open_dir(whoosh_db) else: os.makedirs(whoosh_db) create_idx = create_in(whoosh_db, schema) writer = create_idx.writer() for switch in [True, False]: do_for_post(writer, rand=switch, doc_type=post_type['1']) do_for_wiki(writer, rand=switch, doc_type=post_type['1']) do_for_page(writer, rand=switch, doc_type=post_type['1']) for kind in kind_arr: do_for_app(writer, rand=switch, kind=kind, doc_type=post_type) writer.commit()
kind_arr, define the `type` except Post, Page, Wiki post_type, define the templates for different kind.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/core/tool/run_whoosh.py#L132-L167
bukun/TorCMS
torcms/handlers/publish_handler.py
PublishHandler.echo_class2
def echo_class2(self, catstr=''): ''' 弹出的二级发布菜单 ''' fatherid = catstr[1:] self.write(self.format_class2(fatherid))
python
def echo_class2(self, catstr=''): ''' 弹出的二级发布菜单 ''' fatherid = catstr[1:] self.write(self.format_class2(fatherid))
弹出的二级发布菜单
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/publish_handler.py#L47-L52
bukun/TorCMS
torcms/handlers/publish_handler.py
PublishHandler.view_class1
def view_class1(self, kind_sig): ''' Publishing from 1st range category. ''' dbdata = MCategory.get_parent_list(kind=kind_sig) class1str = '' for rec in dbdata: class1str += ''' <a onclick="select_sub_tag('/publish/2{0}');" class="btn btn-primary" style="display: inline-block;margin:3px;" > {1}</a>'''.format(rec.uid, rec.name) kwd = {'class1str': class1str, 'parentid': '0', 'parentlist': MCategory.get_parent_list()} self.render('misc/publish/publish.html', userinfo=self.userinfo, kwd=kwd)
python
def view_class1(self, kind_sig): ''' Publishing from 1st range category. ''' dbdata = MCategory.get_parent_list(kind=kind_sig) class1str = '' for rec in dbdata: class1str += ''' <a onclick="select_sub_tag('/publish/2{0}');" class="btn btn-primary" style="display: inline-block;margin:3px;" > {1}</a>'''.format(rec.uid, rec.name) kwd = {'class1str': class1str, 'parentid': '0', 'parentlist': MCategory.get_parent_list()} self.render('misc/publish/publish.html', userinfo=self.userinfo, kwd=kwd)
Publishing from 1st range category.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/publish_handler.py#L68-L85
bukun/TorCMS
torcms/handlers/publish_handler.py
PublishHandler.view_class2
def view_class2(self, fatherid=''): ''' Publishing from 2ed range category. ''' if self.is_admin(): pass else: return False kwd = {'class1str': self.format_class2(fatherid), 'parentid': '0', 'parentlist': MCategory.get_parent_list()} if fatherid.endswith('00'): self.render('misc/publish/publish2.html', userinfo=self.userinfo, kwd=kwd) else: catinfo = MCategory.get_by_uid(fatherid) self.redirect('/{1}/_cat_add/{0}'.format(fatherid, router_post[catinfo.kind]))
python
def view_class2(self, fatherid=''): ''' Publishing from 2ed range category. ''' if self.is_admin(): pass else: return False kwd = {'class1str': self.format_class2(fatherid), 'parentid': '0', 'parentlist': MCategory.get_parent_list()} if fatherid.endswith('00'): self.render('misc/publish/publish2.html', userinfo=self.userinfo, kwd=kwd) else: catinfo = MCategory.get_by_uid(fatherid) self.redirect('/{1}/_cat_add/{0}'.format(fatherid, router_post[catinfo.kind]))
Publishing from 2ed range category.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/publish_handler.py#L88-L108
bukun/TorCMS
torcms/model/evaluation_model.py
MEvaluation.app_evaluation_count
def app_evaluation_count(app_id, value=1): ''' Get the Evalution sum. ''' return TabEvaluation.select().where( (TabEvaluation.post_id == app_id) & (TabEvaluation.value == value) ).count()
python
def app_evaluation_count(app_id, value=1): ''' Get the Evalution sum. ''' return TabEvaluation.select().where( (TabEvaluation.post_id == app_id) & (TabEvaluation.value == value) ).count()
Get the Evalution sum.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/evaluation_model.py#L17-L23
bukun/TorCMS
torcms/model/evaluation_model.py
MEvaluation.get_by_signature
def get_by_signature(user_id, app_id): ''' get by user ID, and app ID. ''' try: return TabEvaluation.get( (TabEvaluation.user_id == user_id) & (TabEvaluation.post_id == app_id) ) except: return None
python
def get_by_signature(user_id, app_id): ''' get by user ID, and app ID. ''' try: return TabEvaluation.get( (TabEvaluation.user_id == user_id) & (TabEvaluation.post_id == app_id) ) except: return None
get by user ID, and app ID.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/evaluation_model.py#L26-L35
bukun/TorCMS
torcms/model/evaluation_model.py
MEvaluation.add_or_update
def add_or_update(user_id, app_id, value): ''' Editing evaluation. ''' rec = MEvaluation.get_by_signature(user_id, app_id) if rec: entry = TabEvaluation.update( value=value, ).where(TabEvaluation.uid == rec.uid) entry.execute() else: TabEvaluation.create( uid=tools.get_uuid(), user_id=user_id, post_id=app_id, value=value, )
python
def add_or_update(user_id, app_id, value): ''' Editing evaluation. ''' rec = MEvaluation.get_by_signature(user_id, app_id) if rec: entry = TabEvaluation.update( value=value, ).where(TabEvaluation.uid == rec.uid) entry.execute() else: TabEvaluation.create( uid=tools.get_uuid(), user_id=user_id, post_id=app_id, value=value, )
Editing evaluation.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/evaluation_model.py#L38-L54
bukun/TorCMS
ext/handler/ext_excel.py
ExtExcelHandler.index
def index(self): ''' Index funtion. ''' self.render('ext_excel/index.html', userinfo=self.userinfo, cfg=CMS_CFG, kwd={}, )
python
def index(self): ''' Index funtion. ''' self.render('ext_excel/index.html', userinfo=self.userinfo, cfg=CMS_CFG, kwd={}, )
Index funtion.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/ext/handler/ext_excel.py#L31-L40
bukun/TorCMS
torcms/handlers/page_ajax_handler.py
PageAjaxHandler.view
def view(self, rec): ''' view the post. ''' out_json = { 'uid': rec.uid, 'time_update': rec.time_update, 'title': rec.title, 'cnt_html': tornado.escape.xhtml_unescape(rec.cnt_html), } self.write(json.dumps(out_json))
python
def view(self, rec): ''' view the post. ''' out_json = { 'uid': rec.uid, 'time_update': rec.time_update, 'title': rec.title, 'cnt_html': tornado.escape.xhtml_unescape(rec.cnt_html), } self.write(json.dumps(out_json))
view the post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_ajax_handler.py#L44-L55
bukun/TorCMS
torcms/handlers/page_ajax_handler.py
PageAjaxHandler.j_count_plus
def j_count_plus(self, slug): ''' plus count via ajax. ''' output = {'status': 1 if MWiki.view_count_plus(slug) else 0} return json.dump(output, self)
python
def j_count_plus(self, slug): ''' plus count via ajax. ''' output = {'status': 1 if MWiki.view_count_plus(slug) else 0} return json.dump(output, self)
plus count via ajax.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_ajax_handler.py#L61-L66
bukun/TorCMS
torcms/handlers/page_ajax_handler.py
PageAjaxHandler.p_list
def p_list(self, kind, cur_p='', ): ''' List the post . ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MWiki.total_number(kind) / CMS_CFG['list_num']) kwd = { 'pager': '', 'title': 'Recent pages.', 'kind': kind, 'current_page': current_page_number, 'page_count': MWiki.get_counts(), } self.render('admin/page_ajax/page_list.html', postrecs=MWiki.query_pager_by_kind(kind=kind, current_page_num=current_page_number), kwd=kwd)
python
def p_list(self, kind, cur_p='', ): ''' List the post . ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MWiki.total_number(kind) / CMS_CFG['list_num']) kwd = { 'pager': '', 'title': 'Recent pages.', 'kind': kind, 'current_page': current_page_number, 'page_count': MWiki.get_counts(), } self.render('admin/page_ajax/page_list.html', postrecs=MWiki.query_pager_by_kind(kind=kind, current_page_num=current_page_number), kwd=kwd)
List the post .
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_ajax_handler.py#L68-L92
bukun/TorCMS
torcms/model/user_model.py
MUser.set_sendemail_time
def set_sendemail_time(uid): ''' Set the time that send E-mail to user. ''' entry = TabMember.update( time_email=tools.timestamp(), ).where(TabMember.uid == uid) entry.execute()
python
def set_sendemail_time(uid): ''' Set the time that send E-mail to user. ''' entry = TabMember.update( time_email=tools.timestamp(), ).where(TabMember.uid == uid) entry.execute()
Set the time that send E-mail to user.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L46-L53
bukun/TorCMS
torcms/model/user_model.py
MUser.check_user
def check_user(user_id, u_pass): ''' Checking the password by user's ID. ''' user_count = TabMember.select().where(TabMember.uid == user_id).count() if user_count == 0: return -1 the_user = TabMember.get(uid=user_id) if the_user.user_pass == tools.md5(u_pass): return 1 return 0
python
def check_user(user_id, u_pass): ''' Checking the password by user's ID. ''' user_count = TabMember.select().where(TabMember.uid == user_id).count() if user_count == 0: return -1 the_user = TabMember.get(uid=user_id) if the_user.user_pass == tools.md5(u_pass): return 1 return 0
Checking the password by user's ID.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L66-L76
bukun/TorCMS
torcms/model/user_model.py
MUser.check_user_by_name
def check_user_by_name(user_name, u_pass): ''' Checking the password by user's name. ''' the_query = TabMember.select().where(TabMember.user_name == user_name) if the_query.count() == 0: return -1 the_user = the_query.get() if the_user.user_pass == tools.md5(u_pass): return 1 return 0
python
def check_user_by_name(user_name, u_pass): ''' Checking the password by user's name. ''' the_query = TabMember.select().where(TabMember.user_name == user_name) if the_query.count() == 0: return -1 the_user = the_query.get() if the_user.user_pass == tools.md5(u_pass): return 1 return 0
Checking the password by user's name.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L79-L90
bukun/TorCMS
torcms/model/user_model.py
MUser.update_pass
def update_pass(user_id, newpass): ''' Update the password of a user. ''' out_dic = {'success': False, 'code': '00'} entry = TabMember.update(user_pass=tools.md5(newpass)).where(TabMember.uid == user_id) entry.execute() out_dic['success'] = True return out_dic
python
def update_pass(user_id, newpass): ''' Update the password of a user. ''' out_dic = {'success': False, 'code': '00'} entry = TabMember.update(user_pass=tools.md5(newpass)).where(TabMember.uid == user_id) entry.execute() out_dic['success'] = True return out_dic
Update the password of a user.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L93-L105
bukun/TorCMS
torcms/model/user_model.py
MUser.query_nologin
def query_nologin(): ''' Query the users who do not login recently (90 days). and not send email (120 days). time_model: num * month * hours * minite * second time_login: 3 * 30 * 24 * 60 * 60 time_email: 4 * 30 * 24 * 60 * 60 ''' time_now = tools.timestamp() return TabMember.select().where( ((time_now - TabMember.time_login) > 7776000) & ((time_now - TabMember.time_email) > 10368000) )
python
def query_nologin(): ''' Query the users who do not login recently (90 days). and not send email (120 days). time_model: num * month * hours * minite * second time_login: 3 * 30 * 24 * 60 * 60 time_email: 4 * 30 * 24 * 60 * 60 ''' time_now = tools.timestamp() return TabMember.select().where( ((time_now - TabMember.time_login) > 7776000) & ((time_now - TabMember.time_email) > 10368000) )
Query the users who do not login recently (90 days). and not send email (120 days). time_model: num * month * hours * minite * second time_login: 3 * 30 * 24 * 60 * 60 time_email: 4 * 30 * 24 * 60 * 60
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L108-L120
bukun/TorCMS
torcms/model/user_model.py
MUser.update_info
def update_info(user_id, newemail, extinfo=None): ''' Update the user info by user_id. 21: standsfor invalide E-mail. 91: standsfor unkown reson. ''' if extinfo is None: extinfo = {} out_dic = {'success': False, 'code': '00'} if not tools.check_email_valid(newemail): out_dic['code'] = '21' return out_dic cur_info = MUser.get_by_uid(user_id) cur_extinfo = cur_info.extinfo for key in extinfo: cur_extinfo[key] = extinfo[key] try: entry = TabMember.update( user_email=newemail, extinfo=cur_extinfo ).where( TabMember.uid == user_id ) entry.execute() out_dic['success'] = True except: out_dic['code'] = '91' return out_dic
python
def update_info(user_id, newemail, extinfo=None): ''' Update the user info by user_id. 21: standsfor invalide E-mail. 91: standsfor unkown reson. ''' if extinfo is None: extinfo = {} out_dic = {'success': False, 'code': '00'} if not tools.check_email_valid(newemail): out_dic['code'] = '21' return out_dic cur_info = MUser.get_by_uid(user_id) cur_extinfo = cur_info.extinfo for key in extinfo: cur_extinfo[key] = extinfo[key] try: entry = TabMember.update( user_email=newemail, extinfo=cur_extinfo ).where( TabMember.uid == user_id ) entry.execute() out_dic['success'] = True except: out_dic['code'] = '91' return out_dic
Update the user info by user_id. 21: standsfor invalide E-mail. 91: standsfor unkown reson.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L123-L155
bukun/TorCMS
torcms/model/user_model.py
MUser.update_time_reset_passwd
def update_time_reset_passwd(user_name, the_time): ''' Update the time when user reset passwd. ''' entry = TabMember.update( time_reset_passwd=the_time, ).where(TabMember.user_name == user_name) try: entry.execute() return True except: return False
python
def update_time_reset_passwd(user_name, the_time): ''' Update the time when user reset passwd. ''' entry = TabMember.update( time_reset_passwd=the_time, ).where(TabMember.user_name == user_name) try: entry.execute() return True except: return False
Update the time when user reset passwd.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L158-L169
bukun/TorCMS
torcms/model/user_model.py
MUser.update_role
def update_role(u_name, newprivilege): ''' Update the role of the usr. ''' entry = TabMember.update( role=newprivilege ).where(TabMember.user_name == u_name) try: entry.execute() return True except: return False
python
def update_role(u_name, newprivilege): ''' Update the role of the usr. ''' entry = TabMember.update( role=newprivilege ).where(TabMember.user_name == u_name) try: entry.execute() return True except: return False
Update the role of the usr.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L172-L183
bukun/TorCMS
torcms/model/user_model.py
MUser.update_time_login
def update_time_login(u_name): ''' Update the login time for user. ''' entry = TabMember.update( time_login=tools.timestamp() ).where( TabMember.user_name == u_name ) entry.execute()
python
def update_time_login(u_name): ''' Update the login time for user. ''' entry = TabMember.update( time_login=tools.timestamp() ).where( TabMember.user_name == u_name ) entry.execute()
Update the login time for user.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L186-L195
bukun/TorCMS
torcms/model/user_model.py
MUser.create_user
def create_user(post_data): ''' Create the user. The code used if `False`. 11: standsfor invalid username. 21: standsfor invalide E-mail. 91: standsfor unkown reson. ''' out_dic = {'success': False, 'code': '00'} if not tools.check_username_valid(post_data['user_name']): out_dic['code'] = '11' return out_dic if not tools.check_email_valid(post_data['user_email']): out_dic['code'] = '21' return out_dic try: TabMember.create(uid=tools.get_uuid(), user_name=post_data['user_name'], user_pass=tools.md5(post_data['user_pass']), user_email=post_data['user_email'], role='1000', # ‘1000' as default role. time_create=tools.timestamp(), time_update=tools.timestamp(), time_reset_passwd=tools.timestamp(), time_login=tools.timestamp(), time_email=tools.timestamp()) out_dic['success'] = True except: out_dic['code'] = '91' return out_dic
python
def create_user(post_data): ''' Create the user. The code used if `False`. 11: standsfor invalid username. 21: standsfor invalide E-mail. 91: standsfor unkown reson. ''' out_dic = {'success': False, 'code': '00'} if not tools.check_username_valid(post_data['user_name']): out_dic['code'] = '11' return out_dic if not tools.check_email_valid(post_data['user_email']): out_dic['code'] = '21' return out_dic try: TabMember.create(uid=tools.get_uuid(), user_name=post_data['user_name'], user_pass=tools.md5(post_data['user_pass']), user_email=post_data['user_email'], role='1000', # ‘1000' as default role. time_create=tools.timestamp(), time_update=tools.timestamp(), time_reset_passwd=tools.timestamp(), time_login=tools.timestamp(), time_email=tools.timestamp()) out_dic['success'] = True except: out_dic['code'] = '91' return out_dic
Create the user. The code used if `False`. 11: standsfor invalid username. 21: standsfor invalide E-mail. 91: standsfor unkown reson.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L198-L231
bukun/TorCMS
torcms/model/user_model.py
MUser.delete_by_user_name
def delete_by_user_name(user_name): ''' Delete user in the database by `user_name`. ''' try: del_count = TabMember.delete().where(TabMember.user_name == user_name) del_count.execute() return True except: return False
python
def delete_by_user_name(user_name): ''' Delete user in the database by `user_name`. ''' try: del_count = TabMember.delete().where(TabMember.user_name == user_name) del_count.execute() return True except: return False
Delete user in the database by `user_name`.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L241-L250
bukun/TorCMS
torcms/model/user_model.py
MUser.delete
def delete(user_id): ''' Delele the user in the database by `user_id`. ''' try: del_count = TabMember.delete().where(TabMember.uid == user_id) del_count.execute() return True except: return False
python
def delete(user_id): ''' Delele the user in the database by `user_id`. ''' try: del_count = TabMember.delete().where(TabMember.uid == user_id) del_count.execute() return True except: return False
Delele the user in the database by `user_id`.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L253-L262
bukun/TorCMS
torcms/script/script_sitemap.py
gen_post_map
def gen_post_map(file_name, ext_url=''): ''' Generate the urls for posts. :return: None ''' with open(file_name, 'a') as fout: for kind_key in router_post: recent_posts = MPost.query_all(kind=kind_key, limit=1000000) for recent_post in recent_posts: url = os.path.join(SITE_CFG['site_url'], router_post[recent_post.kind], ext_url, recent_post.uid) fout.write('{url}\n'.format(url=url))
python
def gen_post_map(file_name, ext_url=''): ''' Generate the urls for posts. :return: None ''' with open(file_name, 'a') as fout: for kind_key in router_post: recent_posts = MPost.query_all(kind=kind_key, limit=1000000) for recent_post in recent_posts: url = os.path.join(SITE_CFG['site_url'], router_post[recent_post.kind], ext_url, recent_post.uid) fout.write('{url}\n'.format(url=url))
Generate the urls for posts. :return: None
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_sitemap.py#L12-L25
bukun/TorCMS
torcms/script/script_sitemap.py
gen_wiki_map
def gen_wiki_map(file_name, ext_url=''): ''' Generate the urls for wiki. :return: None ''' # wiki wiki_recs = MWiki.query_all(limit=10000, kind='1') with open(file_name, 'a') as fileout: for rec in wiki_recs: url = os.path.join(SITE_CFG['site_url'], 'wiki' + '/_edit' if ext_url else '', rec.title) fileout.write('{url}\n'.format(url=url)) ## page. page_recs = MWiki.query_all(limit=10000, kind='2') with open(file_name, 'a') as fileout: for rec in page_recs: url = os.path.join(SITE_CFG['site_url'], 'page' + '/_edit' if ext_url else '', rec.uid) fileout.write('{url}\n'.format(url=url))
python
def gen_wiki_map(file_name, ext_url=''): ''' Generate the urls for wiki. :return: None ''' # wiki wiki_recs = MWiki.query_all(limit=10000, kind='1') with open(file_name, 'a') as fileout: for rec in wiki_recs: url = os.path.join(SITE_CFG['site_url'], 'wiki' + '/_edit' if ext_url else '', rec.title) fileout.write('{url}\n'.format(url=url)) ## page. page_recs = MWiki.query_all(limit=10000, kind='2') with open(file_name, 'a') as fileout: for rec in page_recs: url = os.path.join(SITE_CFG['site_url'], 'page' + '/_edit' if ext_url else '', rec.uid) fileout.write('{url}\n'.format(url=url))
Generate the urls for wiki. :return: None
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_sitemap.py#L28-L53
bukun/TorCMS
torcms/script/script_sitemap.py
run_sitemap
def run_sitemap(_): ''' Generate the sitemap file. :param args: args :return: None ''' site_map_file = 'xx_sitemap.txt' if os.path.exists(site_map_file): os.remove(site_map_file) gen_wiki_map(site_map_file) gen_post_map(site_map_file)
python
def run_sitemap(_): ''' Generate the sitemap file. :param args: args :return: None ''' site_map_file = 'xx_sitemap.txt' if os.path.exists(site_map_file): os.remove(site_map_file) gen_wiki_map(site_map_file) gen_post_map(site_map_file)
Generate the sitemap file. :param args: args :return: None
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_sitemap.py#L56-L67
bukun/TorCMS
torcms/script/script_sitemap.py
run_editmap
def run_editmap(_): ''' Generate the urls file for editing. :param args: args :return: None ''' edit_map_file = 'xx_editmap.txt' if os.path.exists(edit_map_file): os.remove(edit_map_file) gen_wiki_map(edit_map_file, ext_url='_edit') gen_post_map(edit_map_file, ext_url='_edit')
python
def run_editmap(_): ''' Generate the urls file for editing. :param args: args :return: None ''' edit_map_file = 'xx_editmap.txt' if os.path.exists(edit_map_file): os.remove(edit_map_file) gen_wiki_map(edit_map_file, ext_url='_edit') gen_post_map(edit_map_file, ext_url='_edit')
Generate the urls file for editing. :param args: args :return: None
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_sitemap.py#L70-L81
bukun/TorCMS
helper_scripts/script_meta_xlsx_import_v2.py
get_meta
def get_meta(catid, sig): ''' Get metadata of dataset via ID. ''' meta_base = './static/dataset_list' if os.path.exists(meta_base): pass else: return False pp_data = {'logo': '', 'kind': '9'} for wroot, wdirs, wfiles in os.walk(meta_base): for wdir in wdirs: if wdir.lower().endswith(sig): # Got the dataset of certain ID. ds_base = pathlib.Path(os.path.join(wroot, wdir)) for uu in ds_base.iterdir(): if uu.name.endswith('.xlsx'): meta_dic = chuli_meta('u' + sig[2:], uu) pp_data['title'] = meta_dic['title'] pp_data['cnt_md'] = meta_dic['anytext'] pp_data['user_name'] = 'admin' pp_data['def_cat_uid'] = catid pp_data['gcat0'] = catid pp_data['def_cat_pid'] = catid[:2] + '00' pp_data['extinfo'] = {} elif uu.name.startswith('thumbnail_'): pp_data['logo'] = os.path.join(wroot, wdir, uu.name).strip('.') return pp_data
python
def get_meta(catid, sig): ''' Get metadata of dataset via ID. ''' meta_base = './static/dataset_list' if os.path.exists(meta_base): pass else: return False pp_data = {'logo': '', 'kind': '9'} for wroot, wdirs, wfiles in os.walk(meta_base): for wdir in wdirs: if wdir.lower().endswith(sig): # Got the dataset of certain ID. ds_base = pathlib.Path(os.path.join(wroot, wdir)) for uu in ds_base.iterdir(): if uu.name.endswith('.xlsx'): meta_dic = chuli_meta('u' + sig[2:], uu) pp_data['title'] = meta_dic['title'] pp_data['cnt_md'] = meta_dic['anytext'] pp_data['user_name'] = 'admin' pp_data['def_cat_uid'] = catid pp_data['gcat0'] = catid pp_data['def_cat_pid'] = catid[:2] + '00' pp_data['extinfo'] = {} elif uu.name.startswith('thumbnail_'): pp_data['logo'] = os.path.join(wroot, wdir, uu.name).strip('.') return pp_data
Get metadata of dataset via ID.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/helper_scripts/script_meta_xlsx_import_v2.py#L29-L59
bukun/TorCMS
torcms/handlers/post_handler.py
update_category
def update_category(uid, post_data): ''' Update the category of the post. :param uid: The ID of the post. Extra info would get by requests. ''' # deprecated # catid = kwargs['catid'] if MCategory.get_by_uid(kwargs.get('catid')) else None # post_data = self.get_post_data() if 'gcat0' in post_data: pass else: return False # Used to update MPost2Category, to keep order. the_cats_arr = [] # Used to update post extinfo. the_cats_dict = {} # for old page. deprecated # def_cate_arr.append('def_cat_uid') def_cate_arr = ['gcat{0}'.format(x) for x in range(10)] for key in def_cate_arr: if key not in post_data: continue if post_data[key] == '' or post_data[key] == '0': continue # 有可能选重复了。保留前面的 if post_data[key] in the_cats_arr: continue the_cats_arr.append(post_data[key] + ' ' * (4 - len(post_data[key]))) the_cats_dict[key] = post_data[key] + ' ' * (4 - len(post_data[key])) # if catid: # def_cat_id = catid if the_cats_arr: def_cat_id = the_cats_arr[0] else: def_cat_id = None if def_cat_id: the_cats_dict['gcat0'] = def_cat_id the_cats_dict['def_cat_uid'] = def_cat_id the_cats_dict['def_cat_pid'] = MCategory.get_by_uid(def_cat_id).pid # Add the category logger.info('Update category: {0}'.format(the_cats_arr)) logger.info('Update category: {0}'.format(the_cats_dict)) MPost.update_jsonb(uid, the_cats_dict) for index, idx_catid in enumerate(the_cats_arr): MPost2Catalog.add_record(uid, idx_catid, index) # Delete the old category if not in post requests. current_infos = MPost2Catalog.query_by_entity_uid(uid, kind='').objects() for cur_info in current_infos: if cur_info.tag_id not in the_cats_arr: MPost2Catalog.remove_relation(uid, cur_info.tag_id)
python
def update_category(uid, post_data): ''' Update the category of the post. :param uid: The ID of the post. Extra info would get by requests. ''' # deprecated # catid = kwargs['catid'] if MCategory.get_by_uid(kwargs.get('catid')) else None # post_data = self.get_post_data() if 'gcat0' in post_data: pass else: return False # Used to update MPost2Category, to keep order. the_cats_arr = [] # Used to update post extinfo. the_cats_dict = {} # for old page. deprecated # def_cate_arr.append('def_cat_uid') def_cate_arr = ['gcat{0}'.format(x) for x in range(10)] for key in def_cate_arr: if key not in post_data: continue if post_data[key] == '' or post_data[key] == '0': continue # 有可能选重复了。保留前面的 if post_data[key] in the_cats_arr: continue the_cats_arr.append(post_data[key] + ' ' * (4 - len(post_data[key]))) the_cats_dict[key] = post_data[key] + ' ' * (4 - len(post_data[key])) # if catid: # def_cat_id = catid if the_cats_arr: def_cat_id = the_cats_arr[0] else: def_cat_id = None if def_cat_id: the_cats_dict['gcat0'] = def_cat_id the_cats_dict['def_cat_uid'] = def_cat_id the_cats_dict['def_cat_pid'] = MCategory.get_by_uid(def_cat_id).pid # Add the category logger.info('Update category: {0}'.format(the_cats_arr)) logger.info('Update category: {0}'.format(the_cats_dict)) MPost.update_jsonb(uid, the_cats_dict) for index, idx_catid in enumerate(the_cats_arr): MPost2Catalog.add_record(uid, idx_catid, index) # Delete the old category if not in post requests. current_infos = MPost2Catalog.query_by_entity_uid(uid, kind='').objects() for cur_info in current_infos: if cur_info.tag_id not in the_cats_arr: MPost2Catalog.remove_relation(uid, cur_info.tag_id)
Update the category of the post. :param uid: The ID of the post. Extra info would get by requests.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L30-L90
bukun/TorCMS
torcms/handlers/post_handler.py
update_label
def update_label(signature, post_data): ''' Update the label when updating. ''' current_tag_infos = MPost2Label.get_by_uid(signature).objects() if 'tags' in post_data: pass else: return False tags_arr = [x.strip() for x in post_data['tags'].split(',')] for tag_name in tags_arr: if tag_name == '': pass else: MPost2Label.add_record(signature, tag_name, 1) for cur_info in current_tag_infos: if cur_info.tag_name in tags_arr: pass else: MPost2Label.remove_relation(signature, cur_info.tag_id)
python
def update_label(signature, post_data): ''' Update the label when updating. ''' current_tag_infos = MPost2Label.get_by_uid(signature).objects() if 'tags' in post_data: pass else: return False tags_arr = [x.strip() for x in post_data['tags'].split(',')] for tag_name in tags_arr: if tag_name == '': pass else: MPost2Label.add_record(signature, tag_name, 1) for cur_info in current_tag_infos: if cur_info.tag_name in tags_arr: pass else: MPost2Label.remove_relation(signature, cur_info.tag_id)
Update the label when updating.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L93-L114
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler.index
def index(self): ''' The default page of POST. ''' self.render('post_{0}/post_index.html'.format(self.kind), userinfo=self.userinfo, kwd={'uid': '', })
python
def index(self): ''' The default page of POST. ''' self.render('post_{0}/post_index.html'.format(self.kind), userinfo=self.userinfo, kwd={'uid': '', })
The default page of POST.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L182-L188
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._gen_uid
def _gen_uid(self): ''' Generate the ID for post. :return: the new ID. ''' cur_uid = self.kind + tools.get_uu4d() while MPost.get_by_uid(cur_uid): cur_uid = self.kind + tools.get_uu4d() return cur_uid
python
def _gen_uid(self): ''' Generate the ID for post. :return: the new ID. ''' cur_uid = self.kind + tools.get_uu4d() while MPost.get_by_uid(cur_uid): cur_uid = self.kind + tools.get_uu4d() return cur_uid
Generate the ID for post. :return: the new ID.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L190-L198
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._get_tmpl_view
def _get_tmpl_view(self, rec): ''' According to the application, each info of it's classification could has different temaplate. :param rec: the App record. :return: the temaplte path. ''' if 'def_cat_uid' in rec.extinfo and rec.extinfo['def_cat_uid'] != '': cat_id = rec.extinfo['def_cat_uid'] elif 'gcat0' in rec.extinfo and rec.extinfo['gcat0'] != '': cat_id = rec.extinfo['gcat0'] else: cat_id = None logger.info('For templates: catid: {0}, filter_view: {1}'.format(cat_id, self.filter_view)) if cat_id and self.filter_view: tmpl = 'autogen/view/view_{0}.html'.format(cat_id) else: tmpl = 'post_{0}/post_view.html'.format(self.kind) return tmpl
python
def _get_tmpl_view(self, rec): ''' According to the application, each info of it's classification could has different temaplate. :param rec: the App record. :return: the temaplte path. ''' if 'def_cat_uid' in rec.extinfo and rec.extinfo['def_cat_uid'] != '': cat_id = rec.extinfo['def_cat_uid'] elif 'gcat0' in rec.extinfo and rec.extinfo['gcat0'] != '': cat_id = rec.extinfo['gcat0'] else: cat_id = None logger.info('For templates: catid: {0}, filter_view: {1}'.format(cat_id, self.filter_view)) if cat_id and self.filter_view: tmpl = 'autogen/view/view_{0}.html'.format(cat_id) else: tmpl = 'post_{0}/post_view.html'.format(self.kind) return tmpl
According to the application, each info of it's classification could has different temaplate. :param rec: the App record. :return: the temaplte path.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L200-L221
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._to_add_with_category
def _to_add_with_category(self, catid): ''' Used for info2. :param catid: the uid of category ''' catinfo = MCategory.get_by_uid(catid) kwd = { 'uid': self._gen_uid(), 'userid': self.userinfo.user_name if self.userinfo else '', 'gcat0': catid, 'parentname': MCategory.get_by_uid(catinfo.pid).name, 'catname': MCategory.get_by_uid(catid).name, } self.render('autogen/add/add_{0}.html'.format(catid), userinfo=self.userinfo, kwd=kwd)
python
def _to_add_with_category(self, catid): ''' Used for info2. :param catid: the uid of category ''' catinfo = MCategory.get_by_uid(catid) kwd = { 'uid': self._gen_uid(), 'userid': self.userinfo.user_name if self.userinfo else '', 'gcat0': catid, 'parentname': MCategory.get_by_uid(catinfo.pid).name, 'catname': MCategory.get_by_uid(catid).name, } self.render('autogen/add/add_{0}.html'.format(catid), userinfo=self.userinfo, kwd=kwd)
Used for info2. :param catid: the uid of category
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L225-L242
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._view_or_add
def _view_or_add(self, uid): ''' Try to get the post. If not, to add the wiki. ''' postinfo = MPost.get_by_uid(uid) if postinfo: self.viewinfo(postinfo) elif self.userinfo: self._to_add(uid=uid) else: self.show404()
python
def _view_or_add(self, uid): ''' Try to get the post. If not, to add the wiki. ''' postinfo = MPost.get_by_uid(uid) if postinfo: self.viewinfo(postinfo) elif self.userinfo: self._to_add(uid=uid) else: self.show404()
Try to get the post. If not, to add the wiki.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L244-L254
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._to_add
def _to_add(self, **kwargs): ''' Used for info1. ''' if 'catid' in kwargs: catid = kwargs['catid'] return self._to_add_with_category(catid) else: if 'uid' in kwargs and MPost.get_by_uid(kwargs['uid']): # todo: # self.redirect('/{0}/edit/{1}'.format(self.app_url_name, uid)) uid = kwargs['uid'] else: uid = '' self.render('post_{0}/post_add.html'.format(self.kind), tag_infos=MCategory.query_all(by_order=True, kind=self.kind), userinfo=self.userinfo, kwd={'uid': uid, })
python
def _to_add(self, **kwargs): ''' Used for info1. ''' if 'catid' in kwargs: catid = kwargs['catid'] return self._to_add_with_category(catid) else: if 'uid' in kwargs and MPost.get_by_uid(kwargs['uid']): # todo: # self.redirect('/{0}/edit/{1}'.format(self.app_url_name, uid)) uid = kwargs['uid'] else: uid = '' self.render('post_{0}/post_add.html'.format(self.kind), tag_infos=MCategory.query_all(by_order=True, kind=self.kind), userinfo=self.userinfo, kwd={'uid': uid, })
Used for info1.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L258-L277
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._to_edit
def _to_edit(self, infoid): ''' render the HTML page for post editing. ''' postinfo = MPost.get_by_uid(infoid) if postinfo: pass else: return self.show404() if 'def_cat_uid' in postinfo.extinfo: catid = postinfo.extinfo['def_cat_uid'] elif 'gcat0' in postinfo.extinfo: catid = postinfo.extinfo['gcat0'] else: catid = '' if len(catid) == 4: pass else: catid = '' catinfo = None p_catinfo = None post2catinfo = MPost2Catalog.get_first_category(postinfo.uid) if post2catinfo: catid = post2catinfo.tag_id catinfo = MCategory.get_by_uid(catid) if catinfo: p_catinfo = MCategory.get_by_uid(catinfo.pid) kwd = { 'gcat0': catid, 'parentname': '', 'catname': '', 'parentlist': MCategory.get_parent_list(), 'userip': self.request.remote_ip, 'extinfo': json.dumps(postinfo.extinfo, indent=2, ensure_ascii=False), } if self.filter_view: tmpl = 'autogen/edit/edit_{0}.html'.format(catid) else: tmpl = 'post_{0}/post_edit.html'.format(self.kind) logger.info('Meta template: {0}'.format(tmpl)) self.render( tmpl, kwd=kwd, postinfo=postinfo, catinfo=catinfo, pcatinfo=p_catinfo, userinfo=self.userinfo, cat_enum=MCategory.get_qian2(catid[:2]), tag_infos=MCategory.query_all(by_order=True, kind=self.kind), tag_infos2=MCategory.query_all(by_order=True, kind=self.kind), app2tag_info=MPost2Catalog.query_by_entity_uid(infoid, kind=self.kind).objects(), app2label_info=MPost2Label.get_by_uid(infoid).objects() )
python
def _to_edit(self, infoid): ''' render the HTML page for post editing. ''' postinfo = MPost.get_by_uid(infoid) if postinfo: pass else: return self.show404() if 'def_cat_uid' in postinfo.extinfo: catid = postinfo.extinfo['def_cat_uid'] elif 'gcat0' in postinfo.extinfo: catid = postinfo.extinfo['gcat0'] else: catid = '' if len(catid) == 4: pass else: catid = '' catinfo = None p_catinfo = None post2catinfo = MPost2Catalog.get_first_category(postinfo.uid) if post2catinfo: catid = post2catinfo.tag_id catinfo = MCategory.get_by_uid(catid) if catinfo: p_catinfo = MCategory.get_by_uid(catinfo.pid) kwd = { 'gcat0': catid, 'parentname': '', 'catname': '', 'parentlist': MCategory.get_parent_list(), 'userip': self.request.remote_ip, 'extinfo': json.dumps(postinfo.extinfo, indent=2, ensure_ascii=False), } if self.filter_view: tmpl = 'autogen/edit/edit_{0}.html'.format(catid) else: tmpl = 'post_{0}/post_edit.html'.format(self.kind) logger.info('Meta template: {0}'.format(tmpl)) self.render( tmpl, kwd=kwd, postinfo=postinfo, catinfo=catinfo, pcatinfo=p_catinfo, userinfo=self.userinfo, cat_enum=MCategory.get_qian2(catid[:2]), tag_infos=MCategory.query_all(by_order=True, kind=self.kind), tag_infos2=MCategory.query_all(by_order=True, kind=self.kind), app2tag_info=MPost2Catalog.query_by_entity_uid(infoid, kind=self.kind).objects(), app2label_info=MPost2Label.get_by_uid(infoid).objects() )
render the HTML page for post editing.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L281-L343
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._gen_last_current_relation
def _gen_last_current_relation(self, post_id): ''' Generate the relation for the post and last post viewed. ''' last_post_id = self.get_secure_cookie('last_post_uid') if last_post_id: last_post_id = last_post_id.decode('utf-8') self.set_secure_cookie('last_post_uid', post_id) if last_post_id and MPost.get_by_uid(last_post_id): self._add_relation(last_post_id, post_id)
python
def _gen_last_current_relation(self, post_id): ''' Generate the relation for the post and last post viewed. ''' last_post_id = self.get_secure_cookie('last_post_uid') if last_post_id: last_post_id = last_post_id.decode('utf-8') self.set_secure_cookie('last_post_uid', post_id) if last_post_id and MPost.get_by_uid(last_post_id): self._add_relation(last_post_id, post_id)
Generate the relation for the post and last post viewed.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L345-L355
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler.redirect_kind
def redirect_kind(self, postinfo): ''' Redirect according the kind of the post. :param postinfo: the postinfo :return: None ''' logger.warning('info kind:{0} '.format(postinfo.kind)) # If not, there must be something wrong. if postinfo.kind == self.kind: pass else: self.redirect('/{0}/{1}'.format(router_post[postinfo.kind], postinfo.uid), permanent=True)
python
def redirect_kind(self, postinfo): ''' Redirect according the kind of the post. :param postinfo: the postinfo :return: None ''' logger.warning('info kind:{0} '.format(postinfo.kind)) # If not, there must be something wrong. if postinfo.kind == self.kind: pass else: self.redirect('/{0}/{1}'.format(router_post[postinfo.kind], postinfo.uid), permanent=True)
Redirect according the kind of the post. :param postinfo: the postinfo :return: None
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L357-L370
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler.viewinfo
def viewinfo(self, postinfo): ''' In infor. ''' self.redirect_kind(postinfo) # ToDo: 原为下面代码。 # ext_catid = postinfo.extinfo['def_cat_uid'] if 'def_cat_uid' in postinfo.extinfo else '' # ext_catid2 = postinfo.extinfo['def_cat_uid'] if 'def_cat_uid' in postinfo.extinfo else None ext_catid = postinfo.extinfo['def_cat_uid'] if 'def_cat_uid' in postinfo.extinfo else '' cat_enum1 = MCategory.get_qian2(ext_catid[:2]) if ext_catid else [] rand_recs, rel_recs = self.fetch_additional_posts(postinfo.uid) self._chuli_cookie_relation(postinfo.uid) catinfo = None p_catinfo = None post2catinfo = MPost2Catalog.get_first_category(postinfo.uid) if post2catinfo: catinfo = MCategory.get_by_uid(post2catinfo.tag_id) if catinfo: p_catinfo = MCategory.get_by_uid(catinfo.pid) kwd = self._the_view_kwd(postinfo) MPost.update_misc(postinfo.uid, count=True) if self.get_current_user() and self.userinfo: MUsage.add_or_update(self.userinfo.uid, postinfo.uid, postinfo.kind) self.set_cookie('user_pass', kwd['cookie_str']) tmpl = self.ext_tmpl_view(postinfo) if self.userinfo: recent_apps = MUsage.query_recent(self.userinfo.uid, postinfo.kind, 6).objects()[1:] else: recent_apps = [] logger.info('The Info Template: {0}'.format(tmpl)) self.render(tmpl, kwd=dict(kwd, **self.ext_view_kwd(postinfo)), postinfo=postinfo, userinfo=self.userinfo, author=postinfo.user_name, # Todo: remove the key `author`. catinfo=catinfo, pcatinfo=p_catinfo, relations=rel_recs, rand_recs=rand_recs, subcats=MCategory.query_sub_cat(p_catinfo.uid), ad_switch=random.randint(1, 18), tag_info=filter(lambda x: not x.tag_name.startswith('_'), MPost2Label.get_by_uid(postinfo.uid).objects()), recent_apps=recent_apps, cat_enum=cat_enum1)
python
def viewinfo(self, postinfo): ''' In infor. ''' self.redirect_kind(postinfo) # ToDo: 原为下面代码。 # ext_catid = postinfo.extinfo['def_cat_uid'] if 'def_cat_uid' in postinfo.extinfo else '' # ext_catid2 = postinfo.extinfo['def_cat_uid'] if 'def_cat_uid' in postinfo.extinfo else None ext_catid = postinfo.extinfo['def_cat_uid'] if 'def_cat_uid' in postinfo.extinfo else '' cat_enum1 = MCategory.get_qian2(ext_catid[:2]) if ext_catid else [] rand_recs, rel_recs = self.fetch_additional_posts(postinfo.uid) self._chuli_cookie_relation(postinfo.uid) catinfo = None p_catinfo = None post2catinfo = MPost2Catalog.get_first_category(postinfo.uid) if post2catinfo: catinfo = MCategory.get_by_uid(post2catinfo.tag_id) if catinfo: p_catinfo = MCategory.get_by_uid(catinfo.pid) kwd = self._the_view_kwd(postinfo) MPost.update_misc(postinfo.uid, count=True) if self.get_current_user() and self.userinfo: MUsage.add_or_update(self.userinfo.uid, postinfo.uid, postinfo.kind) self.set_cookie('user_pass', kwd['cookie_str']) tmpl = self.ext_tmpl_view(postinfo) if self.userinfo: recent_apps = MUsage.query_recent(self.userinfo.uid, postinfo.kind, 6).objects()[1:] else: recent_apps = [] logger.info('The Info Template: {0}'.format(tmpl)) self.render(tmpl, kwd=dict(kwd, **self.ext_view_kwd(postinfo)), postinfo=postinfo, userinfo=self.userinfo, author=postinfo.user_name, # Todo: remove the key `author`. catinfo=catinfo, pcatinfo=p_catinfo, relations=rel_recs, rand_recs=rand_recs, subcats=MCategory.query_sub_cat(p_catinfo.uid), ad_switch=random.randint(1, 18), tag_info=filter(lambda x: not x.tag_name.startswith('_'), MPost2Label.get_by_uid(postinfo.uid).objects()), recent_apps=recent_apps, cat_enum=cat_enum1)
In infor.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L373-L429
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._the_view_kwd
def _the_view_kwd(self, postinfo): ''' Generate the kwd dict for view. :param postinfo: the postinfo :return: dict ''' kwd = { 'pager': '', 'url': self.request.uri, 'cookie_str': tools.get_uuid(), 'daohangstr': '', 'signature': postinfo.uid, 'tdesc': '', 'eval_0': MEvaluation.app_evaluation_count(postinfo.uid, 0), 'eval_1': MEvaluation.app_evaluation_count(postinfo.uid, 1), 'login': 1 if self.get_current_user() else 0, 'has_image': 0, 'parentlist': MCategory.get_parent_list(), 'parentname': '', 'catname': '', 'router': router_post[postinfo.kind] } return kwd
python
def _the_view_kwd(self, postinfo): ''' Generate the kwd dict for view. :param postinfo: the postinfo :return: dict ''' kwd = { 'pager': '', 'url': self.request.uri, 'cookie_str': tools.get_uuid(), 'daohangstr': '', 'signature': postinfo.uid, 'tdesc': '', 'eval_0': MEvaluation.app_evaluation_count(postinfo.uid, 0), 'eval_1': MEvaluation.app_evaluation_count(postinfo.uid, 1), 'login': 1 if self.get_current_user() else 0, 'has_image': 0, 'parentlist': MCategory.get_parent_list(), 'parentname': '', 'catname': '', 'router': router_post[postinfo.kind] } return kwd
Generate the kwd dict for view. :param postinfo: the postinfo :return: dict
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L431-L453
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler.fetch_additional_posts
def fetch_additional_posts(self, uid): ''' fetch the rel_recs, and random recs when view the post. ''' cats = MPost2Catalog.query_by_entity_uid(uid, kind=self.kind) cat_uid_arr = [] for cat_rec in cats: cat_uid = cat_rec.tag_id cat_uid_arr.append(cat_uid) logger.info('info category: {0}'.format(cat_uid_arr)) rel_recs = MRelation.get_app_relations(uid, 8, kind=self.kind).objects() logger.info('rel_recs count: {0}'.format(rel_recs.count())) if cat_uid_arr: rand_recs = MPost.query_cat_random(cat_uid_arr[0], limit=4 - rel_recs.count() + 4) else: rand_recs = MPost.query_random(num=4 - rel_recs.count() + 4, kind=self.kind) return rand_recs, rel_recs
python
def fetch_additional_posts(self, uid): ''' fetch the rel_recs, and random recs when view the post. ''' cats = MPost2Catalog.query_by_entity_uid(uid, kind=self.kind) cat_uid_arr = [] for cat_rec in cats: cat_uid = cat_rec.tag_id cat_uid_arr.append(cat_uid) logger.info('info category: {0}'.format(cat_uid_arr)) rel_recs = MRelation.get_app_relations(uid, 8, kind=self.kind).objects() logger.info('rel_recs count: {0}'.format(rel_recs.count())) if cat_uid_arr: rand_recs = MPost.query_cat_random(cat_uid_arr[0], limit=4 - rel_recs.count() + 4) else: rand_recs = MPost.query_random(num=4 - rel_recs.count() + 4, kind=self.kind) return rand_recs, rel_recs
fetch the rel_recs, and random recs when view the post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L455-L472
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._add_relation
def _add_relation(self, f_uid, t_uid): ''' Add the relation. And the from and to, should have different weight. :param f_uid: the uid of `from` post. :param t_uid: the uid of `to` post. :return: return True if the relation has been succesfully added. ''' if not MPost.get_by_uid(t_uid): return False if f_uid == t_uid: return False # 针对分类进行处理。只有落入相同分类的,才加1 f_cats = MPost2Catalog.query_by_entity_uid(f_uid) t_cats = MPost2Catalog.query_by_entity_uid(t_uid) flag = False for f_cat in f_cats: for t_cat in t_cats: if f_cat.tag_id == t_cat.tag_id: flag = True if flag: pass else: return False # 双向关联,但权重不一样. MRelation.add_relation(f_uid, t_uid, 2) MRelation.add_relation(t_uid, f_uid, 1) return True
python
def _add_relation(self, f_uid, t_uid): ''' Add the relation. And the from and to, should have different weight. :param f_uid: the uid of `from` post. :param t_uid: the uid of `to` post. :return: return True if the relation has been succesfully added. ''' if not MPost.get_by_uid(t_uid): return False if f_uid == t_uid: return False # 针对分类进行处理。只有落入相同分类的,才加1 f_cats = MPost2Catalog.query_by_entity_uid(f_uid) t_cats = MPost2Catalog.query_by_entity_uid(t_uid) flag = False for f_cat in f_cats: for t_cat in t_cats: if f_cat.tag_id == t_cat.tag_id: flag = True if flag: pass else: return False # 双向关联,但权重不一样. MRelation.add_relation(f_uid, t_uid, 2) MRelation.add_relation(t_uid, f_uid, 1) return True
Add the relation. And the from and to, should have different weight. :param f_uid: the uid of `from` post. :param t_uid: the uid of `to` post. :return: return True if the relation has been succesfully added.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L474-L501
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler.fetch_post_data
def fetch_post_data(self): ''' fetch post accessed data. post_data, and ext_dic. ''' post_data = {} ext_dic = {} for key in self.request.arguments: if key.startswith('ext_') or key.startswith('tag_'): ext_dic[key] = self.get_argument(key) else: post_data[key] = self.get_arguments(key)[0] post_data['user_name'] = self.userinfo.user_name post_data['kind'] = self.kind # append external infor. if 'tags' in post_data: ext_dic['def_tag_arr'] = [x.strip() for x in post_data['tags'].strip().strip(',').split(',')] ext_dic = dict(ext_dic, **self.ext_post_data(postdata=post_data)) return (post_data, ext_dic)
python
def fetch_post_data(self): ''' fetch post accessed data. post_data, and ext_dic. ''' post_data = {} ext_dic = {} for key in self.request.arguments: if key.startswith('ext_') or key.startswith('tag_'): ext_dic[key] = self.get_argument(key) else: post_data[key] = self.get_arguments(key)[0] post_data['user_name'] = self.userinfo.user_name post_data['kind'] = self.kind # append external infor. if 'tags' in post_data: ext_dic['def_tag_arr'] = [x.strip() for x in post_data['tags'].strip().strip(',').split(',')] ext_dic = dict(ext_dic, **self.ext_post_data(postdata=post_data)) return (post_data, ext_dic)
fetch post accessed data. post_data, and ext_dic.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L503-L525
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler.add
def add(self, **kwargs): ''' in infor. ''' if 'uid' in kwargs: uid = kwargs['uid'] else: uid = self._gen_uid() post_data, ext_dic = self.fetch_post_data() if 'gcat0' in post_data: pass else: return False if 'valid' in post_data: post_data['valid'] = int(post_data['valid']) else: post_data['valid'] = 1 ext_dic['def_uid'] = uid ext_dic['gcat0'] = post_data['gcat0'] ext_dic['def_cat_uid'] = post_data['gcat0'] MPost.modify_meta(ext_dic['def_uid'], post_data, extinfo=ext_dic) kwargs.pop('uid', None) # delete `uid` if exists in kwargs self._add_download_entity(ext_dic) # self.update_tag(uid=ext_dic['def_uid'], **kwargs) update_category(ext_dic['def_uid'], post_data) update_label(ext_dic['def_uid'], post_data) # self.update_label(uid) # cele_gen_whoosh.delay() tornado.ioloop.IOLoop.instance().add_callback(self.cele_gen_whoosh) self.redirect('/{0}/{1}'.format(router_post[self.kind], uid))
python
def add(self, **kwargs): ''' in infor. ''' if 'uid' in kwargs: uid = kwargs['uid'] else: uid = self._gen_uid() post_data, ext_dic = self.fetch_post_data() if 'gcat0' in post_data: pass else: return False if 'valid' in post_data: post_data['valid'] = int(post_data['valid']) else: post_data['valid'] = 1 ext_dic['def_uid'] = uid ext_dic['gcat0'] = post_data['gcat0'] ext_dic['def_cat_uid'] = post_data['gcat0'] MPost.modify_meta(ext_dic['def_uid'], post_data, extinfo=ext_dic) kwargs.pop('uid', None) # delete `uid` if exists in kwargs self._add_download_entity(ext_dic) # self.update_tag(uid=ext_dic['def_uid'], **kwargs) update_category(ext_dic['def_uid'], post_data) update_label(ext_dic['def_uid'], post_data) # self.update_label(uid) # cele_gen_whoosh.delay() tornado.ioloop.IOLoop.instance().add_callback(self.cele_gen_whoosh) self.redirect('/{0}/{1}'.format(router_post[self.kind], uid))
in infor.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L531-L570
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler.update
def update(self, uid): ''' in infor. ''' postinfo = MPost.get_by_uid(uid) if postinfo.kind == self.kind: pass else: return False post_data, ext_dic = self.fetch_post_data() if 'gcat0' in post_data: pass else: return False if 'valid' in post_data: post_data['valid'] = int(post_data['valid']) else: post_data['valid'] = postinfo.valid ext_dic['def_uid'] = str(uid) cnt_old = tornado.escape.xhtml_unescape(postinfo.cnt_md).strip() cnt_new = post_data['cnt_md'].strip() if cnt_old == cnt_new: pass else: MPostHist.create_post_history(postinfo) MPost.modify_meta(uid, post_data, extinfo=ext_dic) self._add_download_entity(ext_dic) # self.update_tag(uid=uid) update_category(uid, post_data) update_label(uid, post_data) # self.update_label(uid) logger.info('post kind:' + self.kind) # cele_gen_whoosh.delay() tornado.ioloop.IOLoop.instance().add_callback(self.cele_gen_whoosh) self.redirect('/{0}/{1}'.format(router_post[postinfo.kind], uid))
python
def update(self, uid): ''' in infor. ''' postinfo = MPost.get_by_uid(uid) if postinfo.kind == self.kind: pass else: return False post_data, ext_dic = self.fetch_post_data() if 'gcat0' in post_data: pass else: return False if 'valid' in post_data: post_data['valid'] = int(post_data['valid']) else: post_data['valid'] = postinfo.valid ext_dic['def_uid'] = str(uid) cnt_old = tornado.escape.xhtml_unescape(postinfo.cnt_md).strip() cnt_new = post_data['cnt_md'].strip() if cnt_old == cnt_new: pass else: MPostHist.create_post_history(postinfo) MPost.modify_meta(uid, post_data, extinfo=ext_dic) self._add_download_entity(ext_dic) # self.update_tag(uid=uid) update_category(uid, post_data) update_label(uid, post_data) # self.update_label(uid) logger.info('post kind:' + self.kind) # cele_gen_whoosh.delay() tornado.ioloop.IOLoop.instance().add_callback(self.cele_gen_whoosh) self.redirect('/{0}/{1}'.format(router_post[postinfo.kind], uid))
in infor.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L575-L618
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._delete
def _delete(self, *args, **kwargs): ''' delete the post. ''' _ = kwargs uid = args[0] current_infor = MPost.get_by_uid(uid) if MPost.delete(uid): tslug = MCategory.get_by_uid(current_infor.extinfo['def_cat_uid']) MCategory.update_count(current_infor.extinfo['def_cat_uid']) if router_post[self.kind] == 'info': url = "filter" id_dk8 = current_infor.extinfo['def_cat_uid'] else: url = "list" id_dk8 = tslug.slug self.redirect('/{0}/{1}'.format(url, id_dk8)) else: self.redirect('/{0}/{1}'.format(router_post[self.kind], uid))
python
def _delete(self, *args, **kwargs): ''' delete the post. ''' _ = kwargs uid = args[0] current_infor = MPost.get_by_uid(uid) if MPost.delete(uid): tslug = MCategory.get_by_uid(current_infor.extinfo['def_cat_uid']) MCategory.update_count(current_infor.extinfo['def_cat_uid']) if router_post[self.kind] == 'info': url = "filter" id_dk8 = current_infor.extinfo['def_cat_uid'] else: url = "list" id_dk8 = tslug.slug self.redirect('/{0}/{1}'.format(url, id_dk8)) else: self.redirect('/{0}/{1}'.format(router_post[self.kind], uid))
delete the post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L622-L647
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._chuli_cookie_relation
def _chuli_cookie_relation(self, app_id): ''' The current Info and the Info viewed last should have some relation. And the last viewed Info could be found from cookie. ''' last_app_uid = self.get_secure_cookie('use_app_uid') if last_app_uid: last_app_uid = last_app_uid.decode('utf-8') self.set_secure_cookie('use_app_uid', app_id) if last_app_uid and MPost.get_by_uid(last_app_uid): self._add_relation(last_app_uid, app_id)
python
def _chuli_cookie_relation(self, app_id): ''' The current Info and the Info viewed last should have some relation. And the last viewed Info could be found from cookie. ''' last_app_uid = self.get_secure_cookie('use_app_uid') if last_app_uid: last_app_uid = last_app_uid.decode('utf-8') self.set_secure_cookie('use_app_uid', app_id) if last_app_uid and MPost.get_by_uid(last_app_uid): self._add_relation(last_app_uid, app_id)
The current Info and the Info viewed last should have some relation. And the last viewed Info could be found from cookie.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L649-L659
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._to_edit_kind
def _to_edit_kind(self, post_uid): ''' Show the page for changing the category. ''' if self.userinfo and self.userinfo.role[1] >= '3': pass else: self.redirect('/') postinfo = MPost.get_by_uid(post_uid, ) json_cnt = json.dumps(postinfo.extinfo, indent=True) kwd = {} self.render('man_info/post_kind.html', postinfo=postinfo, sig_dic=router_post, userinfo=self.userinfo, json_cnt=json_cnt, kwd=kwd)
python
def _to_edit_kind(self, post_uid): ''' Show the page for changing the category. ''' if self.userinfo and self.userinfo.role[1] >= '3': pass else: self.redirect('/') postinfo = MPost.get_by_uid(post_uid, ) json_cnt = json.dumps(postinfo.extinfo, indent=True) kwd = {} self.render('man_info/post_kind.html', postinfo=postinfo, sig_dic=router_post, userinfo=self.userinfo, json_cnt=json_cnt, kwd=kwd)
Show the page for changing the category.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L691-L707
bukun/TorCMS
torcms/handlers/post_handler.py
PostHandler._change_kind
def _change_kind(self, post_uid): ''' To modify the category of the post, and kind. ''' post_data = self.get_post_data() logger.info('admin post update: {0}'.format(post_data)) MPost.update_misc(post_uid, kind=post_data['kcat']) # self.update_category(post_uid) update_category(post_uid, post_data) self.redirect('/{0}/{1}'.format(router_post[post_data['kcat']], post_uid))
python
def _change_kind(self, post_uid): ''' To modify the category of the post, and kind. ''' post_data = self.get_post_data() logger.info('admin post update: {0}'.format(post_data)) MPost.update_misc(post_uid, kind=post_data['kcat']) # self.update_category(post_uid) update_category(post_uid, post_data) self.redirect('/{0}/{1}'.format(router_post[post_data['kcat']], post_uid))
To modify the category of the post, and kind.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L711-L724
bukun/TorCMS
torcms/handlers/entity_handler.py
EntityHandler.list
def list(self, cur_p=''): ''' Lists of the entities. ''' current_page_number = int(cur_p) if cur_p else 1 current_page_number = 1 if current_page_number < 1 else current_page_number kwd = { 'current_page': current_page_number } recs = MEntity.get_all_pager(current_page_num=current_page_number) self.render('misc/entity/entity_list.html', imgs=recs, cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
python
def list(self, cur_p=''): ''' Lists of the entities. ''' current_page_number = int(cur_p) if cur_p else 1 current_page_number = 1 if current_page_number < 1 else current_page_number kwd = { 'current_page': current_page_number } recs = MEntity.get_all_pager(current_page_num=current_page_number) self.render('misc/entity/entity_list.html', imgs=recs, cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
Lists of the entities.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/entity_handler.py#L71-L86
bukun/TorCMS
torcms/handlers/entity_handler.py
EntityHandler.down
def down(self, down_uid): ''' Download the entity by UID. ''' down_url = MPost.get_by_uid(down_uid).extinfo.get('tag__file_download', '') print('=' * 40) print(down_url) str_down_url = str(down_url)[15:] if down_url: ment_id = MEntity.get_id_by_impath(str_down_url) if ment_id: MEntity2User.create_entity2user(ment_id, self.userinfo.uid) return True else: return False
python
def down(self, down_uid): ''' Download the entity by UID. ''' down_url = MPost.get_by_uid(down_uid).extinfo.get('tag__file_download', '') print('=' * 40) print(down_url) str_down_url = str(down_url)[15:] if down_url: ment_id = MEntity.get_id_by_impath(str_down_url) if ment_id: MEntity2User.create_entity2user(ment_id, self.userinfo.uid) return True else: return False
Download the entity by UID.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/entity_handler.py#L89-L105
bukun/TorCMS
torcms/handlers/entity_handler.py
EntityHandler.to_add
def to_add(self): ''' To add the entity. ''' kwd = { 'pager': '', } self.render('misc/entity/entity_add.html', cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
python
def to_add(self): ''' To add the entity. ''' kwd = { 'pager': '', } self.render('misc/entity/entity_add.html', cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
To add the entity.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/entity_handler.py#L108-L118
bukun/TorCMS
torcms/handlers/entity_handler.py
EntityHandler.add_entity
def add_entity(self): ''' Add the entity. All the information got from the post data. ''' post_data = self.get_post_data() if 'kind' in post_data: if post_data['kind'] == '1': self.add_pic(post_data) elif post_data['kind'] == '2': self.add_pdf(post_data) elif post_data['kind'] == '3': self.add_url(post_data) else: pass else: self.add_pic(post_data)
python
def add_entity(self): ''' Add the entity. All the information got from the post data. ''' post_data = self.get_post_data() if 'kind' in post_data: if post_data['kind'] == '1': self.add_pic(post_data) elif post_data['kind'] == '2': self.add_pdf(post_data) elif post_data['kind'] == '3': self.add_url(post_data) else: pass else: self.add_pic(post_data)
Add the entity. All the information got from the post data.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/entity_handler.py#L121-L137
bukun/TorCMS
torcms/handlers/entity_handler.py
EntityHandler.add_pic
def add_pic(self, post_data): ''' Adding the picture. ''' img_entity = self.request.files['file'][0] filename = img_entity["filename"] if filename and allowed_file(filename): pass else: return False _, hou = os.path.splitext(filename) signature = str(uuid.uuid1()) outfilename = '{0}{1}'.format(signature, hou) outpath = 'static/upload/{0}'.format(signature[:2]) if os.path.exists(outpath): pass else: os.makedirs(outpath) with open(os.path.join(outpath, outfilename), "wb") as fileout: fileout.write(img_entity["body"]) path_save = os.path.join(signature[:2], outfilename) sig_save = os.path.join(signature[:2], signature) imgpath = os.path.join(outpath, signature + '_m.jpg') imgpath_sm = os.path.join(outpath, signature + '_sm.jpg') ptr_image = Image.open(os.path.join('static/upload', path_save)) tmpl_size = (768, 768) thub_size = (256, 256) (imgwidth, imgheight) = ptr_image.size if imgwidth < tmpl_size[0] and imgheight < tmpl_size[1]: tmpl_size = (imgwidth, imgheight) ptr_image.thumbnail(tmpl_size) im0 = ptr_image.convert('RGB') im0.save(imgpath, 'JPEG') im0.thumbnail(thub_size) im0.save(imgpath_sm, 'JPEG') create_pic = MEntity.create_entity(signature, path_save, post_data['desc'] if 'desc' in post_data else '', kind=post_data['kind'] if 'kind' in post_data else '1') if self.entity_ajax == False: self.redirect('/entity/{0}_m.jpg'.format(sig_save)) else: if create_pic: output = {'path_save': imgpath} else: output = {'path_save': ''} return json.dump(output, self)
python
def add_pic(self, post_data): ''' Adding the picture. ''' img_entity = self.request.files['file'][0] filename = img_entity["filename"] if filename and allowed_file(filename): pass else: return False _, hou = os.path.splitext(filename) signature = str(uuid.uuid1()) outfilename = '{0}{1}'.format(signature, hou) outpath = 'static/upload/{0}'.format(signature[:2]) if os.path.exists(outpath): pass else: os.makedirs(outpath) with open(os.path.join(outpath, outfilename), "wb") as fileout: fileout.write(img_entity["body"]) path_save = os.path.join(signature[:2], outfilename) sig_save = os.path.join(signature[:2], signature) imgpath = os.path.join(outpath, signature + '_m.jpg') imgpath_sm = os.path.join(outpath, signature + '_sm.jpg') ptr_image = Image.open(os.path.join('static/upload', path_save)) tmpl_size = (768, 768) thub_size = (256, 256) (imgwidth, imgheight) = ptr_image.size if imgwidth < tmpl_size[0] and imgheight < tmpl_size[1]: tmpl_size = (imgwidth, imgheight) ptr_image.thumbnail(tmpl_size) im0 = ptr_image.convert('RGB') im0.save(imgpath, 'JPEG') im0.thumbnail(thub_size) im0.save(imgpath_sm, 'JPEG') create_pic = MEntity.create_entity(signature, path_save, post_data['desc'] if 'desc' in post_data else '', kind=post_data['kind'] if 'kind' in post_data else '1') if self.entity_ajax == False: self.redirect('/entity/{0}_m.jpg'.format(sig_save)) else: if create_pic: output = {'path_save': imgpath} else: output = {'path_save': ''} return json.dump(output, self)
Adding the picture.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/entity_handler.py#L140-L193
bukun/TorCMS
torcms/handlers/entity_handler.py
EntityHandler.add_pdf
def add_pdf(self, post_data): ''' Adding the pdf file. ''' img_entity = self.request.files['file'][0] img_desc = post_data['desc'] filename = img_entity["filename"] if filename and allowed_file_pdf(filename): pass else: return False _, hou = os.path.splitext(filename) signature = str(uuid.uuid1()) outfilename = '{0}{1}'.format(signature, hou) outpath = 'static/upload/{0}'.format(signature[:2]) if os.path.exists(outpath): pass else: os.makedirs(outpath) with open(os.path.join(outpath, outfilename), "wb") as fout: fout.write(img_entity["body"]) sig_save = os.path.join(signature[:2], signature) path_save = os.path.join(signature[:2], outfilename) create_pdf = MEntity.create_entity(signature, path_save, img_desc, kind=post_data['kind'] if 'kind' in post_data else '2') if self.entity_ajax == False: self.redirect('/entity/{0}{1}'.format(sig_save, hou.lower())) else: if create_pdf: output = {'path_save': path_save} else: output = {'path_save': ''} return json.dump(output, self)
python
def add_pdf(self, post_data): ''' Adding the pdf file. ''' img_entity = self.request.files['file'][0] img_desc = post_data['desc'] filename = img_entity["filename"] if filename and allowed_file_pdf(filename): pass else: return False _, hou = os.path.splitext(filename) signature = str(uuid.uuid1()) outfilename = '{0}{1}'.format(signature, hou) outpath = 'static/upload/{0}'.format(signature[:2]) if os.path.exists(outpath): pass else: os.makedirs(outpath) with open(os.path.join(outpath, outfilename), "wb") as fout: fout.write(img_entity["body"]) sig_save = os.path.join(signature[:2], signature) path_save = os.path.join(signature[:2], outfilename) create_pdf = MEntity.create_entity(signature, path_save, img_desc, kind=post_data['kind'] if 'kind' in post_data else '2') if self.entity_ajax == False: self.redirect('/entity/{0}{1}'.format(sig_save, hou.lower())) else: if create_pdf: output = {'path_save': path_save} else: output = {'path_save': ''} return json.dump(output, self)
Adding the pdf file.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/entity_handler.py#L196-L232
bukun/TorCMS
torcms/handlers/entity_handler.py
EntityHandler.add_url
def add_url(self, post_data): ''' Adding the URL as entity. ''' img_desc = post_data['desc'] img_path = post_data['file1'] cur_uid = tools.get_uudd(4) while MEntity.get_by_uid(cur_uid): cur_uid = tools.get_uudd(4) MEntity.create_entity(cur_uid, img_path, img_desc, kind=post_data['kind'] if 'kind' in post_data else '3') kwd = { 'kind': post_data['kind'] if 'kind' in post_data else '3', } self.render('misc/entity/entity_view.html', filename=img_path, cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
python
def add_url(self, post_data): ''' Adding the URL as entity. ''' img_desc = post_data['desc'] img_path = post_data['file1'] cur_uid = tools.get_uudd(4) while MEntity.get_by_uid(cur_uid): cur_uid = tools.get_uudd(4) MEntity.create_entity(cur_uid, img_path, img_desc, kind=post_data['kind'] if 'kind' in post_data else '3') kwd = { 'kind': post_data['kind'] if 'kind' in post_data else '3', } self.render('misc/entity/entity_view.html', filename=img_path, cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
Adding the URL as entity.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/entity_handler.py#L235-L253
bukun/TorCMS
torcms/handlers/user_handler.py
UserHandler.p_changepassword
def p_changepassword(self): ''' Changing password. ''' post_data = self.get_post_data() usercheck = MUser.check_user(self.userinfo.uid, post_data['rawpass']) if usercheck == 1: MUser.update_pass(self.userinfo.uid, post_data['user_pass']) output = {'changepass ': usercheck} else: output = {'changepass ': 0} return json.dump(output, self)
python
def p_changepassword(self): ''' Changing password. ''' post_data = self.get_post_data() usercheck = MUser.check_user(self.userinfo.uid, post_data['rawpass']) if usercheck == 1: MUser.update_pass(self.userinfo.uid, post_data['user_pass']) output = {'changepass ': usercheck} else: output = {'changepass ': 0} return json.dump(output, self)
Changing password.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/user_handler.py#L120-L133
bukun/TorCMS
torcms/handlers/user_handler.py
UserHandler.p_changeinfo
def p_changeinfo(self): ''' Change Infor via Ajax. ''' post_data, def_dic = self.fetch_post_data() usercheck = MUser.check_user(self.userinfo.uid, post_data['rawpass']) if usercheck == 1: MUser.update_info(self.userinfo.uid, post_data['user_email'], extinfo=def_dic) output = {'changeinfo ': usercheck} else: output = {'changeinfo ': 0} return json.dump(output, self)
python
def p_changeinfo(self): ''' Change Infor via Ajax. ''' post_data, def_dic = self.fetch_post_data() usercheck = MUser.check_user(self.userinfo.uid, post_data['rawpass']) if usercheck == 1: MUser.update_info(self.userinfo.uid, post_data['user_email'], extinfo=def_dic) output = {'changeinfo ': usercheck} else: output = {'changeinfo ': 0} return json.dump(output, self)
Change Infor via Ajax.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/user_handler.py#L136-L149
bukun/TorCMS
torcms/handlers/user_handler.py
UserHandler.fetch_post_data
def fetch_post_data(self): ''' fetch post accessed data. post_data, and ext_dic. ''' post_data = {} ext_dic = {} for key in self.request.arguments: if key.startswith('def_'): ext_dic[key] = self.get_argument(key) else: post_data[key] = self.get_arguments(key)[0] post_data['user_name'] = self.userinfo.user_name ext_dic = dict(ext_dic, **self.ext_post_data(postdata=post_data)) return (post_data, ext_dic)
python
def fetch_post_data(self): ''' fetch post accessed data. post_data, and ext_dic. ''' post_data = {} ext_dic = {} for key in self.request.arguments: if key.startswith('def_'): ext_dic[key] = self.get_argument(key) else: post_data[key] = self.get_arguments(key)[0] post_data['user_name'] = self.userinfo.user_name ext_dic = dict(ext_dic, **self.ext_post_data(postdata=post_data)) return (post_data, ext_dic)
fetch post accessed data. post_data, and ext_dic.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/user_handler.py#L151-L167
bukun/TorCMS
torcms/handlers/user_handler.py
UserHandler.__check_valid
def __check_valid(self, post_data): ''' To check if the user is succesfully created. Return the status code dict. ''' user_create_status = {'success': False, 'code': '00'} if not tools.check_username_valid(post_data['user_name']): user_create_status['code'] = '11' return user_create_status elif not tools.check_email_valid(post_data['user_email']): user_create_status['code'] = '21' return user_create_status elif MUser.get_by_name(post_data['user_name']): user_create_status['code'] = '12' return user_create_status elif MUser.get_by_email(post_data['user_email']): user_create_status['code'] = '22' return user_create_status user_create_status['success'] = True return user_create_status
python
def __check_valid(self, post_data): ''' To check if the user is succesfully created. Return the status code dict. ''' user_create_status = {'success': False, 'code': '00'} if not tools.check_username_valid(post_data['user_name']): user_create_status['code'] = '11' return user_create_status elif not tools.check_email_valid(post_data['user_email']): user_create_status['code'] = '21' return user_create_status elif MUser.get_by_name(post_data['user_name']): user_create_status['code'] = '12' return user_create_status elif MUser.get_by_email(post_data['user_email']): user_create_status['code'] = '22' return user_create_status user_create_status['success'] = True return user_create_status
To check if the user is succesfully created. Return the status code dict.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/user_handler.py#L333-L354
bukun/TorCMS
torcms/handlers/user_handler.py
UserHandler.json_register
def json_register(self): ''' The first char of 'code' stands for the different field. '1' for user_name '2' for user_email '3' for user_pass '4' for user_role The seconde char of 'code' stands for different status. '1' for invalide '2' for already exists. ''' # user_create_status = {'success': False, 'code': '00'} post_data = self.get_post_data() user_create_status = self.__check_valid(post_data) if not user_create_status['success']: return json.dump(user_create_status, self) form = SumForm(self.request.arguments) if form.validate(): user_create_status = MUser.create_user(post_data) logger.info('user_register_status: {0}'.format(user_create_status)) return json.dump(user_create_status, self) return json.dump(user_create_status, self)
python
def json_register(self): ''' The first char of 'code' stands for the different field. '1' for user_name '2' for user_email '3' for user_pass '4' for user_role The seconde char of 'code' stands for different status. '1' for invalide '2' for already exists. ''' # user_create_status = {'success': False, 'code': '00'} post_data = self.get_post_data() user_create_status = self.__check_valid(post_data) if not user_create_status['success']: return json.dump(user_create_status, self) form = SumForm(self.request.arguments) if form.validate(): user_create_status = MUser.create_user(post_data) logger.info('user_register_status: {0}'.format(user_create_status)) return json.dump(user_create_status, self) return json.dump(user_create_status, self)
The first char of 'code' stands for the different field. '1' for user_name '2' for user_email '3' for user_pass '4' for user_role The seconde char of 'code' stands for different status. '1' for invalide '2' for already exists.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/user_handler.py#L439-L462
bukun/TorCMS
torcms/handlers/user_handler.py
UserHandler.json_changeinfo
def json_changeinfo(self): ''' The first char of 'code' stands for the different field. '1' for user_name '2' for user_email '3' for user_pass '4' for user_role The seconde char of 'code' stands for different status. '1' for invalide '2' for already exists. ''' # user_create_status = {'success': False, 'code': '00'} post_data = self.get_post_data() is_user_passed = MUser.check_user(self.userinfo.uid, post_data['rawpass']) if is_user_passed == 1: user_create_status = self.__check_valid_info(post_data) if not user_create_status['success']: return json.dump(user_create_status, self) form_info = SumFormInfo(self.request.arguments) if form_info.validate(): user_create_status = MUser.update_info(self.userinfo.uid, post_data['user_email']) return json.dump(user_create_status, self) return json.dump(user_create_status, self) return False
python
def json_changeinfo(self): ''' The first char of 'code' stands for the different field. '1' for user_name '2' for user_email '3' for user_pass '4' for user_role The seconde char of 'code' stands for different status. '1' for invalide '2' for already exists. ''' # user_create_status = {'success': False, 'code': '00'} post_data = self.get_post_data() is_user_passed = MUser.check_user(self.userinfo.uid, post_data['rawpass']) if is_user_passed == 1: user_create_status = self.__check_valid_info(post_data) if not user_create_status['success']: return json.dump(user_create_status, self) form_info = SumFormInfo(self.request.arguments) if form_info.validate(): user_create_status = MUser.update_info(self.userinfo.uid, post_data['user_email']) return json.dump(user_create_status, self) return json.dump(user_create_status, self) return False
The first char of 'code' stands for the different field. '1' for user_name '2' for user_email '3' for user_pass '4' for user_role The seconde char of 'code' stands for different status. '1' for invalide '2' for already exists.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/user_handler.py#L464-L493
bukun/TorCMS
torcms/handlers/user_handler.py
UserHandler.json_changepass
def json_changepass(self): ''' The first char of 'code' stands for the different field. '1' for user_name '2' for user_email '3' for user_pass '4' for user_role The seconde char of 'code' stands for different status. '1' for invalide '2' for already exists. ''' # user_create_status = {'success': False, 'code': '00'} # Not used currently. post_data = self.get_post_data() check_usr_status = MUser.check_user(self.userinfo.uid, post_data['rawpass']) if check_usr_status == 1: user_create_status = self.__check_valid_pass(post_data) if not user_create_status['success']: return json.dump(user_create_status, self) form_pass = SumFormPass(self.request.arguments) if form_pass.validate(): MUser.update_pass(self.userinfo.uid, post_data['user_pass']) return json.dump(user_create_status, self) return json.dump(user_create_status, self) return False
python
def json_changepass(self): ''' The first char of 'code' stands for the different field. '1' for user_name '2' for user_email '3' for user_pass '4' for user_role The seconde char of 'code' stands for different status. '1' for invalide '2' for already exists. ''' # user_create_status = {'success': False, 'code': '00'} # Not used currently. post_data = self.get_post_data() check_usr_status = MUser.check_user(self.userinfo.uid, post_data['rawpass']) if check_usr_status == 1: user_create_status = self.__check_valid_pass(post_data) if not user_create_status['success']: return json.dump(user_create_status, self) form_pass = SumFormPass(self.request.arguments) if form_pass.validate(): MUser.update_pass(self.userinfo.uid, post_data['user_pass']) return json.dump(user_create_status, self) return json.dump(user_create_status, self) return False
The first char of 'code' stands for the different field. '1' for user_name '2' for user_email '3' for user_pass '4' for user_role The seconde char of 'code' stands for different status. '1' for invalide '2' for already exists.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/user_handler.py#L495-L526
bukun/TorCMS
torcms/handlers/user_handler.py
UserHandler.login
def login(self): ''' user login. ''' post_data = self.get_post_data() if 'next' in post_data: next_url = post_data['next'] else: next_url = '/' u_name = post_data['user_name'] u_pass = post_data['user_pass'] result = MUser.check_user_by_name(u_name, u_pass) # Todo: the kwd should remove from the codes. if result == 1: self.set_secure_cookie("user", u_name) MUser.update_time_login(u_name) self.redirect(next_url) elif result == 0: self.set_status(401) self.render('user/user_relogin.html', cfg=config.CMS_CFG, kwd={ 'info': '密码验证出错,请重新登陆。', 'link': '/user/login', }, userinfo=self.userinfo) elif result == -1: self.set_status(401) self.render('misc/html/404.html', cfg=config.CMS_CFG, kwd={ 'info': '没有这个用户', 'link': '/user/login', }, userinfo=self.userinfo) else: self.set_status(305) self.redirect("{0}".format(next_url))
python
def login(self): ''' user login. ''' post_data = self.get_post_data() if 'next' in post_data: next_url = post_data['next'] else: next_url = '/' u_name = post_data['user_name'] u_pass = post_data['user_pass'] result = MUser.check_user_by_name(u_name, u_pass) # Todo: the kwd should remove from the codes. if result == 1: self.set_secure_cookie("user", u_name) MUser.update_time_login(u_name) self.redirect(next_url) elif result == 0: self.set_status(401) self.render('user/user_relogin.html', cfg=config.CMS_CFG, kwd={ 'info': '密码验证出错,请重新登陆。', 'link': '/user/login', }, userinfo=self.userinfo) elif result == -1: self.set_status(401) self.render('misc/html/404.html', cfg=config.CMS_CFG, kwd={ 'info': '没有这个用户', 'link': '/user/login', }, userinfo=self.userinfo) else: self.set_status(305) self.redirect("{0}".format(next_url))
user login.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/user_handler.py#L540-L582
bukun/TorCMS
torcms/handlers/user_handler.py
UserHandler.p_to_find
def p_to_find(self, ): ''' To find, pager. ''' kwd = { 'pager': '', } self.render('user/user_find_list.html', kwd=kwd, view=MUser.get_by_keyword(""), cfg=config.CMS_CFG, userinfo=self.userinfo)
python
def p_to_find(self, ): ''' To find, pager. ''' kwd = { 'pager': '', } self.render('user/user_find_list.html', kwd=kwd, view=MUser.get_by_keyword(""), cfg=config.CMS_CFG, userinfo=self.userinfo)
To find, pager.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/user_handler.py#L584-L596
bukun/TorCMS
torcms/handlers/user_handler.py
UserHandler.find
def find(self, keyword=None, cur_p=''): ''' find by keyword. ''' if not keyword: self.__to_find__(cur_p) kwd = { 'pager': '', 'title': '查找结果', } self.render(self.wrap_tmpl('user/{sig}user_find_list.html'), kwd=kwd, view=MUser.get_by_keyword(keyword), cfg=config.CMS_CFG, userinfo=self.userinfo)
python
def find(self, keyword=None, cur_p=''): ''' find by keyword. ''' if not keyword: self.__to_find__(cur_p) kwd = { 'pager': '', 'title': '查找结果', } self.render(self.wrap_tmpl('user/{sig}user_find_list.html'), kwd=kwd, view=MUser.get_by_keyword(keyword), cfg=config.CMS_CFG, userinfo=self.userinfo)
find by keyword.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/user_handler.py#L598-L616
bukun/TorCMS
torcms/handlers/user_handler.py
UserHandler.reset_password
def reset_password(self): ''' Do reset password :return: ''' post_data = self.get_post_data() if 'email' in post_data: userinfo = MUser.get_by_email(post_data['email']) if tools.timestamp() - userinfo.time_reset_passwd < 70: self.set_status(400) kwd = { 'info': '两次重置密码时间应该大于1分钟', 'link': '/user/reset-password', } self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) return False if userinfo: timestamp = tools.timestamp() passwd = userinfo.user_pass username = userinfo.user_name hash_str = tools.md5(username + str(timestamp) + passwd) url_reset = '{0}/user/reset-passwd?u={1}&t={2}&p={3}'.format( config.SITE_CFG['site_url'], username, timestamp, hash_str) email_cnt = '''<div>请查看下面的信息,并<span style="color:red">谨慎操作</span>:</div> <div>您在"{0}"网站({1})申请了密码重置,如果确定要进行密码重置,请打开下面链接:</div> <div><a href={2}>{2}</a></div> <div>如果无法确定本信息的有效性,请忽略本邮件。</div>'''.format(config.SMTP_CFG['name'], config.SITE_CFG['site_url'], url_reset) if send_mail([userinfo.user_email], "{0}|密码重置".format(config.SMTP_CFG['name']), email_cnt): MUser.update_time_reset_passwd(username, timestamp) self.set_status(200) logger.info('password has been reset.') return True self.set_status(400) return False self.set_status(400) return False self.set_status(400) return False
python
def reset_password(self): ''' Do reset password :return: ''' post_data = self.get_post_data() if 'email' in post_data: userinfo = MUser.get_by_email(post_data['email']) if tools.timestamp() - userinfo.time_reset_passwd < 70: self.set_status(400) kwd = { 'info': '两次重置密码时间应该大于1分钟', 'link': '/user/reset-password', } self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) return False if userinfo: timestamp = tools.timestamp() passwd = userinfo.user_pass username = userinfo.user_name hash_str = tools.md5(username + str(timestamp) + passwd) url_reset = '{0}/user/reset-passwd?u={1}&t={2}&p={3}'.format( config.SITE_CFG['site_url'], username, timestamp, hash_str) email_cnt = '''<div>请查看下面的信息,并<span style="color:red">谨慎操作</span>:</div> <div>您在"{0}"网站({1})申请了密码重置,如果确定要进行密码重置,请打开下面链接:</div> <div><a href={2}>{2}</a></div> <div>如果无法确定本信息的有效性,请忽略本邮件。</div>'''.format(config.SMTP_CFG['name'], config.SITE_CFG['site_url'], url_reset) if send_mail([userinfo.user_email], "{0}|密码重置".format(config.SMTP_CFG['name']), email_cnt): MUser.update_time_reset_passwd(username, timestamp) self.set_status(200) logger.info('password has been reset.') return True self.set_status(400) return False self.set_status(400) return False self.set_status(400) return False
Do reset password :return:
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/user_handler.py#L647-L695
bukun/TorCMS
torcms/handlers/user_handler.py
UserHandler.gen_passwd
def gen_passwd(self): ''' reseting password ''' post_data = self.get_post_data() userinfo = MUser.get_by_name(post_data['u']) sub_timestamp = int(post_data['t']) cur_timestamp = tools.timestamp() if cur_timestamp - sub_timestamp < 600 and cur_timestamp > sub_timestamp: pass else: kwd = { 'info': '密码重置已超时!', 'link': '/user/reset-password', } self.set_status(400) self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) hash_str = tools.md5(userinfo.user_name + post_data['t'] + userinfo.user_pass) if hash_str == post_data['p']: pass else: kwd = { 'info': '密码重置验证出错!', 'link': '/user/reset-password', } self.set_status(400) self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo, ) new_passwd = tools.get_uu8d() MUser.update_pass(userinfo.uid, new_passwd) kwd = { 'user_name': userinfo.user_name, 'new_pass': new_passwd, } self.render('user/user_show_pass.html', cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo, )
python
def gen_passwd(self): ''' reseting password ''' post_data = self.get_post_data() userinfo = MUser.get_by_name(post_data['u']) sub_timestamp = int(post_data['t']) cur_timestamp = tools.timestamp() if cur_timestamp - sub_timestamp < 600 and cur_timestamp > sub_timestamp: pass else: kwd = { 'info': '密码重置已超时!', 'link': '/user/reset-password', } self.set_status(400) self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) hash_str = tools.md5(userinfo.user_name + post_data['t'] + userinfo.user_pass) if hash_str == post_data['p']: pass else: kwd = { 'info': '密码重置验证出错!', 'link': '/user/reset-password', } self.set_status(400) self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo, ) new_passwd = tools.get_uu8d() MUser.update_pass(userinfo.uid, new_passwd) kwd = { 'user_name': userinfo.user_name, 'new_pass': new_passwd, } self.render('user/user_show_pass.html', cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo, )
reseting password
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/user_handler.py#L697-L741
bukun/TorCMS
torcms/handlers/sys_handler.py
SysHandler.set_language
def set_language(self, language): ''' Set the cookie for locale. ''' if language == 'ZH': self.set_cookie('ulocale', 'zh_CN') self.set_cookie('blocale', 'zh_CN') else: self.set_cookie('ulocale', 'en_US') self.set_cookie('blocale', 'en_US')
python
def set_language(self, language): ''' Set the cookie for locale. ''' if language == 'ZH': self.set_cookie('ulocale', 'zh_CN') self.set_cookie('blocale', 'zh_CN') else: self.set_cookie('ulocale', 'en_US') self.set_cookie('blocale', 'en_US')
Set the cookie for locale.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/sys_handler.py#L54-L63
bukun/TorCMS
ext_script/autocrud/func_gen_html.py
gen_radio_view
def gen_radio_view(sig_dic): ''' for checkbox ''' view_zuoxiang = ''' <div class="col-sm-4"><span class="des">{0}</span></div> <div class="col-sm-8"> '''.format(sig_dic['zh']) dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = '''<span class="input_text"> {{% if '{0}' in postinfo.extinfo and postinfo.extinfo['{0}'] == "{1}" %}} {2} {{% end %}} </span>'''.format(sig_dic['en'], key, dic_tmp[key]) view_zuoxiang += tmp_str view_zuoxiang += '''</div>''' return view_zuoxiang
python
def gen_radio_view(sig_dic): ''' for checkbox ''' view_zuoxiang = ''' <div class="col-sm-4"><span class="des">{0}</span></div> <div class="col-sm-8"> '''.format(sig_dic['zh']) dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = '''<span class="input_text"> {{% if '{0}' in postinfo.extinfo and postinfo.extinfo['{0}'] == "{1}" %}} {2} {{% end %}} </span>'''.format(sig_dic['en'], key, dic_tmp[key]) view_zuoxiang += tmp_str view_zuoxiang += '''</div>''' return view_zuoxiang
for checkbox
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/ext_script/autocrud/func_gen_html.py#L23-L42
bukun/TorCMS
ext_script/autocrud/func_gen_html.py
gen_checkbox_view
def gen_checkbox_view(sig_dic): ''' for checkbox ''' view_zuoxiang = ''' <div class="col-sm-4"><span class="des">{0}</span></div> <div class="col-sm-8"> '''.format(sig_dic['zh']) dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = ''' <span> {{% if "{0}" in postinfo.extinfo["{1}"] %}} {2} {{% end %}} </span> '''.format(key, sig_dic['en'], dic_tmp[key]) view_zuoxiang += tmp_str view_zuoxiang += '''</div>''' return view_zuoxiang
python
def gen_checkbox_view(sig_dic): ''' for checkbox ''' view_zuoxiang = ''' <div class="col-sm-4"><span class="des">{0}</span></div> <div class="col-sm-8"> '''.format(sig_dic['zh']) dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = ''' <span> {{% if "{0}" in postinfo.extinfo["{1}"] %}} {2} {{% end %}} </span> '''.format(key, sig_dic['en'], dic_tmp[key]) view_zuoxiang += tmp_str view_zuoxiang += '''</div>''' return view_zuoxiang
for checkbox
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/ext_script/autocrud/func_gen_html.py#L45-L66
bukun/TorCMS
ext_script/autocrud/func_gen_html.py
gen_select_view
def gen_select_view(sig_dic): ''' HTML view, for selection. ''' option_str = '' dic_tmp = sig_dic['dic'] for key, val in dic_tmp.items(): tmp_str = ''' {{% if '{sig_en}' in postinfo.extinfo %}} {{% set tmp_var = postinfo.extinfo["{sig_en}"] %}} {{% if tmp_var == "{sig_key}" %}} {sig_dic} {{% end %}} {{% end %}} '''.format(sig_en=sig_dic['en'], sig_key=key, sig_dic=val) option_str += tmp_str return ''' <div class="row"> <div class="col-sm-4"><span class="des"><strong>{sig_zh}</strong></span></div> <div class="col-sm-8"> {option_str} </div></div> '''.format(sig_zh=sig_dic['zh'], option_str=option_str)
python
def gen_select_view(sig_dic): ''' HTML view, for selection. ''' option_str = '' dic_tmp = sig_dic['dic'] for key, val in dic_tmp.items(): tmp_str = ''' {{% if '{sig_en}' in postinfo.extinfo %}} {{% set tmp_var = postinfo.extinfo["{sig_en}"] %}} {{% if tmp_var == "{sig_key}" %}} {sig_dic} {{% end %}} {{% end %}} '''.format(sig_en=sig_dic['en'], sig_key=key, sig_dic=val) option_str += tmp_str return ''' <div class="row"> <div class="col-sm-4"><span class="des"><strong>{sig_zh}</strong></span></div> <div class="col-sm-8"> {option_str} </div></div> '''.format(sig_zh=sig_dic['zh'], option_str=option_str)
HTML view, for selection.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/ext_script/autocrud/func_gen_html.py#L69-L92
bukun/TorCMS
ext_script/autocrud/func_gen_html.py
gen_radio_list
def gen_radio_list(sig_dic): ''' For generating List view HTML file for RADIO. for each item. ''' view_zuoxiang = '''<span class="iga_pd_val">''' dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = '''{{% if postinfo.extinfo['{0}'][0] == "{1}" %}} {2} {{% end %}} '''.format(sig_dic['en'], key, dic_tmp[key]) view_zuoxiang += tmp_str view_zuoxiang += '''</span>''' return view_zuoxiang
python
def gen_radio_list(sig_dic): ''' For generating List view HTML file for RADIO. for each item. ''' view_zuoxiang = '''<span class="iga_pd_val">''' dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = '''{{% if postinfo.extinfo['{0}'][0] == "{1}" %}} {2} {{% end %}} '''.format(sig_dic['en'], key, dic_tmp[key]) view_zuoxiang += tmp_str view_zuoxiang += '''</span>''' return view_zuoxiang
For generating List view HTML file for RADIO. for each item.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/ext_script/autocrud/func_gen_html.py#L118-L132
bukun/TorCMS
ext_script/autocrud/func_gen_html.py
gen_checkbox_list
def gen_checkbox_list(sig_dic): ''' For generating List view HTML file for CHECKBOX. for each item. ''' view_zuoxiang = '''<span class="iga_pd_val">''' dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = '''{{% if "{0}" in postinfo.extinfo["{1}"] %}} {2} {{% end %}} '''.format(key, sig_dic['en'], dic_tmp[key]) view_zuoxiang += tmp_str view_zuoxiang += '''</span>''' return view_zuoxiang
python
def gen_checkbox_list(sig_dic): ''' For generating List view HTML file for CHECKBOX. for each item. ''' view_zuoxiang = '''<span class="iga_pd_val">''' dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = '''{{% if "{0}" in postinfo.extinfo["{1}"] %}} {2} {{% end %}} '''.format(key, sig_dic['en'], dic_tmp[key]) view_zuoxiang += tmp_str view_zuoxiang += '''</span>''' return view_zuoxiang
For generating List view HTML file for CHECKBOX. for each item.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/ext_script/autocrud/func_gen_html.py#L135-L149
bukun/TorCMS
ext_script/autocrud/func_gen_html.py
gen_select_list
def gen_select_list(sig_dic): ''' For generating List view HTML file for SELECT. for each item. ''' view_jushi = '''<span class="label label-primary" style="margin-right:10px">''' dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = '''{{% if '{0}' in postinfo.extinfo and postinfo.extinfo["{0}"][0] == "{1}" %}} {2} {{% end %}}'''.format(sig_dic['en'], key, dic_tmp[key]) view_jushi += tmp_str view_jushi += '''</span>''' return view_jushi
python
def gen_select_list(sig_dic): ''' For generating List view HTML file for SELECT. for each item. ''' view_jushi = '''<span class="label label-primary" style="margin-right:10px">''' dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = '''{{% if '{0}' in postinfo.extinfo and postinfo.extinfo["{0}"][0] == "{1}" %}} {2} {{% end %}}'''.format(sig_dic['en'], key, dic_tmp[key]) view_jushi += tmp_str view_jushi += '''</span>''' return view_jushi
For generating List view HTML file for SELECT. for each item.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/ext_script/autocrud/func_gen_html.py#L152-L166
bukun/TorCMS
torcms/script/autocrud/func_gen_html.py
gen_input_add
def gen_input_add(sig_dic): ''' Adding for HTML Input control. ''' if sig_dic['en'] == 'tag_file_download': html_str = HTML_TPL_DICT['input_add_download'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=sig_dic['type'] ) else: html_str = HTML_TPL_DICT['input_add'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=sig_dic['type'] ) return html_str
python
def gen_input_add(sig_dic): ''' Adding for HTML Input control. ''' if sig_dic['en'] == 'tag_file_download': html_str = HTML_TPL_DICT['input_add_download'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=sig_dic['type'] ) else: html_str = HTML_TPL_DICT['input_add'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=sig_dic['type'] ) return html_str
Adding for HTML Input control.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/func_gen_html.py#L10-L28
bukun/TorCMS
torcms/script/autocrud/func_gen_html.py
gen_input_edit
def gen_input_edit(sig_dic): ''' Editing for HTML input control. ''' if sig_dic['en'] == 'tag_file_download': html_str = HTML_TPL_DICT['input_edit_download'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=sig_dic['type'] ) else: html_str = HTML_TPL_DICT['input_edit'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=sig_dic['type'] ) return html_str
python
def gen_input_edit(sig_dic): ''' Editing for HTML input control. ''' if sig_dic['en'] == 'tag_file_download': html_str = HTML_TPL_DICT['input_edit_download'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=sig_dic['type'] ) else: html_str = HTML_TPL_DICT['input_edit'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=sig_dic['type'] ) return html_str
Editing for HTML input control.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/func_gen_html.py#L31-L49
bukun/TorCMS
torcms/script/autocrud/func_gen_html.py
gen_input_view
def gen_input_view(sig_dic): ''' Viewing the HTML text. ''' if sig_dic['en'] == 'tag_file_download': html_str = HTML_TPL_DICT['input_view_download'].format( sig_zh=sig_dic['zh'], sig_unit=sig_dic['dic'][1] ) elif sig_dic['en'] in ['tag_access_link', 'tag_dmoz_url', 'tag_online_link', 'tag_event_url', 'tag_expert_home', 'tag_pic_url']: html_str = HTML_TPL_DICT['input_view_link'].format( sig_dic['en'], sig_dic['zh'], sig_dic['dic'][1] ) else: html_str = HTML_TPL_DICT['input_view'].format( sig_dic['en'], sig_dic['zh'], sig_dic['dic'][1] ) return html_str
python
def gen_input_view(sig_dic): ''' Viewing the HTML text. ''' if sig_dic['en'] == 'tag_file_download': html_str = HTML_TPL_DICT['input_view_download'].format( sig_zh=sig_dic['zh'], sig_unit=sig_dic['dic'][1] ) elif sig_dic['en'] in ['tag_access_link', 'tag_dmoz_url', 'tag_online_link', 'tag_event_url', 'tag_expert_home', 'tag_pic_url']: html_str = HTML_TPL_DICT['input_view_link'].format( sig_dic['en'], sig_dic['zh'], sig_dic['dic'][1] ) else: html_str = HTML_TPL_DICT['input_view'].format( sig_dic['en'], sig_dic['zh'], sig_dic['dic'][1] ) return html_str
Viewing the HTML text.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/func_gen_html.py#L52-L76
bukun/TorCMS
torcms/script/autocrud/func_gen_html.py
gen_radio_add
def gen_radio_add(sig_dic): ''' Adding for HTML radio control. ''' # html_zuoxiang = ''' # <label for="{0}"><span> # <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"></a> {1}</span> # '''.format(sig['en'], sig['zh']) # each item for radio. radio_control_str = '' dic_tmp = sig_dic['dic'] for key, val in dic_tmp.items(): tmp_str = ''' <input id="{0}" name="{0}" type="radio" class="form-control" value="{1}">{2} '''.format(sig_dic['en'], key, val) radio_control_str += tmp_str # html_zuoxiang += '''</label>''' return '''<label for="{sig_en}"><span> <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"> </a>{sig_zh}</span> {radio_str}</label> '''.format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], radio_str=radio_control_str )
python
def gen_radio_add(sig_dic): ''' Adding for HTML radio control. ''' # html_zuoxiang = ''' # <label for="{0}"><span> # <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"></a> {1}</span> # '''.format(sig['en'], sig['zh']) # each item for radio. radio_control_str = '' dic_tmp = sig_dic['dic'] for key, val in dic_tmp.items(): tmp_str = ''' <input id="{0}" name="{0}" type="radio" class="form-control" value="{1}">{2} '''.format(sig_dic['en'], key, val) radio_control_str += tmp_str # html_zuoxiang += '''</label>''' return '''<label for="{sig_en}"><span> <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"> </a>{sig_zh}</span> {radio_str}</label> '''.format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], radio_str=radio_control_str )
Adding for HTML radio control.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/func_gen_html.py#L79-L107
bukun/TorCMS
torcms/script/autocrud/func_gen_html.py
gen_radio_edit
def gen_radio_edit(sig_dic): ''' editing for HTML radio control. ''' edit_zuoxiang = '''7 <label for="{0}"><span> <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"> </a>{1}</span> '''.format(sig_dic['en'], sig_dic['zh']) dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = ''' <input id="{0}" name="{0}" type="radio" class="form-control" value="{1}" {{% if '{0}' in postinfo.extinfo and postinfo.extinfo['{0}'] == '{1}' %}} checked {{% end %}} >{2} '''.format(sig_dic['en'], key, dic_tmp[key]) edit_zuoxiang += tmp_str edit_zuoxiang += '''</label>''' return edit_zuoxiang
python
def gen_radio_edit(sig_dic): ''' editing for HTML radio control. ''' edit_zuoxiang = '''7 <label for="{0}"><span> <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"> </a>{1}</span> '''.format(sig_dic['en'], sig_dic['zh']) dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = ''' <input id="{0}" name="{0}" type="radio" class="form-control" value="{1}" {{% if '{0}' in postinfo.extinfo and postinfo.extinfo['{0}'] == '{1}' %}} checked {{% end %}} >{2} '''.format(sig_dic['en'], key, dic_tmp[key]) edit_zuoxiang += tmp_str edit_zuoxiang += '''</label>''' return edit_zuoxiang
editing for HTML radio control.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/func_gen_html.py#L110-L132
bukun/TorCMS
torcms/script/autocrud/func_gen_html.py
gen_checkbox_add
def gen_checkbox_add(sig_dic): ''' for checkbox ''' html_wuneisheshi = '''<label for="{0}"><span> <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"> </a>{1}</span>'''.format(sig_dic['en'], sig_dic['zh']) dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = ''' <input id="{0}" name="{0}" type="checkbox" class="form-control" value="{1}">{2} '''.format(sig_dic['en'], key, dic_tmp[key]) html_wuneisheshi += tmp_str html_wuneisheshi += '''</label>''' return html_wuneisheshi
python
def gen_checkbox_add(sig_dic): ''' for checkbox ''' html_wuneisheshi = '''<label for="{0}"><span> <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"> </a>{1}</span>'''.format(sig_dic['en'], sig_dic['zh']) dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = ''' <input id="{0}" name="{0}" type="checkbox" class="form-control" value="{1}">{2} '''.format(sig_dic['en'], key, dic_tmp[key]) html_wuneisheshi += tmp_str html_wuneisheshi += '''</label>''' return html_wuneisheshi
for checkbox
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/func_gen_html.py#L157-L173
bukun/TorCMS
torcms/script/autocrud/func_gen_html.py
gen_checkbox_edit
def gen_checkbox_edit(sig_dic): ''' for checkbox ''' edit_wuneisheshi = '''<label for="{0}"><span> <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"> </a>{1}</span> '''.format(sig_dic['en'], sig_dic['zh']) dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = ''' <input id="{0}" name="{0}" type="checkbox" class="form-control" value="{1}" {{% if "{1}" in postinfo.extinfo["{0}"] %}} checked="checked" {{% end %}} >{2} '''.format(sig_dic['en'], key, dic_tmp[key]) edit_wuneisheshi += tmp_str edit_wuneisheshi += '''</label>''' return edit_wuneisheshi
python
def gen_checkbox_edit(sig_dic): ''' for checkbox ''' edit_wuneisheshi = '''<label for="{0}"><span> <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"> </a>{1}</span> '''.format(sig_dic['en'], sig_dic['zh']) dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = ''' <input id="{0}" name="{0}" type="checkbox" class="form-control" value="{1}" {{% if "{1}" in postinfo.extinfo["{0}"] %}} checked="checked" {{% end %}} >{2} '''.format(sig_dic['en'], key, dic_tmp[key]) edit_wuneisheshi += tmp_str edit_wuneisheshi += '''</label>''' return edit_wuneisheshi
for checkbox
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/func_gen_html.py#L176-L196
bukun/TorCMS
torcms/script/autocrud/func_gen_html.py
gen_select_add
def gen_select_add(sig_dic): ''' Adding for select control. :param sig_dic: html_media_type = { 'en': 'tag_media_type', 'zh': 'Media_type', 'dic': {1: 'Document', 2: 'Data', 3: 'Program'}, 'type': 'select', } ''' option_str = '' for key, val in sig_dic['dic'].items(): tmp_str = '''<option value="{0}">{1}</option>'''.format(key, val) option_str += tmp_str return '''<div class="form-group"> <label for="{sig_en}" class="col-sm-2 control-label"><span> <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"></a> {sig_zh}</span></label> <div class="col-sm-10"><select id="{sig_en}" name="{sig_en}" class="form-control"> {option_str}</select></div></div> '''.format(sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], option_str=option_str)
python
def gen_select_add(sig_dic): ''' Adding for select control. :param sig_dic: html_media_type = { 'en': 'tag_media_type', 'zh': 'Media_type', 'dic': {1: 'Document', 2: 'Data', 3: 'Program'}, 'type': 'select', } ''' option_str = '' for key, val in sig_dic['dic'].items(): tmp_str = '''<option value="{0}">{1}</option>'''.format(key, val) option_str += tmp_str return '''<div class="form-group"> <label for="{sig_en}" class="col-sm-2 control-label"><span> <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"></a> {sig_zh}</span></label> <div class="col-sm-10"><select id="{sig_en}" name="{sig_en}" class="form-control"> {option_str}</select></div></div> '''.format(sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], option_str=option_str)
Adding for select control. :param sig_dic: html_media_type = { 'en': 'tag_media_type', 'zh': 'Media_type', 'dic': {1: 'Document', 2: 'Data', 3: 'Program'}, 'type': 'select', }
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/func_gen_html.py#L223-L247
bukun/TorCMS
torcms/model/post_model.py
MPost.query_recent_most
def query_recent_most(num=8, recent=30): ''' Query the records from database that recently updated. :param num: the number that will returned. :param recent: the number of days recent. ''' time_that = int(time.time()) - recent * 24 * 3600 return TabPost.select().where( TabPost.time_update > time_that ).order_by( TabPost.view_count.desc() ).limit(num)
python
def query_recent_most(num=8, recent=30): ''' Query the records from database that recently updated. :param num: the number that will returned. :param recent: the number of days recent. ''' time_that = int(time.time()) - recent * 24 * 3600 return TabPost.select().where( TabPost.time_update > time_that ).order_by( TabPost.view_count.desc() ).limit(num)
Query the records from database that recently updated. :param num: the number that will returned. :param recent: the number of days recent.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_model.py#L26-L37
bukun/TorCMS
torcms/model/post_model.py
MPost.delete
def delete(uid): ''' Delete by uid ''' q_u1 = TabPostHist.delete().where(TabPostHist.post_id == uid) q_u1.execute() q_u2 = TabRel.delete().where(TabRel.post_f_id == uid or TabRel.post_t_id == uid) q_u2.execute() q_u3 = TabCollect.delete().where(TabCollect.post_id == uid) q_u3.execute() q_u4 = TabPost2Tag.delete().where(TabPost2Tag.post_id == uid) q_u4.execute() q_u5 = TabUsage.delete().where(TabUsage.post_id == uid) q_u5.execute() reply_arr = [] for reply in TabUser2Reply.select().where(TabUser2Reply.reply_id == uid): reply_arr.append(reply.reply_id.uid) q_u6 = TabUser2Reply.delete().where(TabUser2Reply.reply_id == uid) q_u6.execute() for replyid in reply_arr: TabReply.delete().where(TabReply.uid == replyid).execute() q_u7 = TabEvaluation.delete().where(TabEvaluation.post_id == uid) q_u7.execute() q_u8 = TabRating.delete().where(TabRating.post_id == uid) q_u8.execute() return MHelper.delete(TabPost, uid)
python
def delete(uid): ''' Delete by uid ''' q_u1 = TabPostHist.delete().where(TabPostHist.post_id == uid) q_u1.execute() q_u2 = TabRel.delete().where(TabRel.post_f_id == uid or TabRel.post_t_id == uid) q_u2.execute() q_u3 = TabCollect.delete().where(TabCollect.post_id == uid) q_u3.execute() q_u4 = TabPost2Tag.delete().where(TabPost2Tag.post_id == uid) q_u4.execute() q_u5 = TabUsage.delete().where(TabUsage.post_id == uid) q_u5.execute() reply_arr = [] for reply in TabUser2Reply.select().where(TabUser2Reply.reply_id == uid): reply_arr.append(reply.reply_id.uid) q_u6 = TabUser2Reply.delete().where(TabUser2Reply.reply_id == uid) q_u6.execute() for replyid in reply_arr: TabReply.delete().where(TabReply.uid == replyid).execute() q_u7 = TabEvaluation.delete().where(TabEvaluation.post_id == uid) q_u7.execute() q_u8 = TabRating.delete().where(TabRating.post_id == uid) q_u8.execute() return MHelper.delete(TabPost, uid)
Delete by uid
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_model.py#L40-L70
bukun/TorCMS
torcms/model/post_model.py
MPost.__update_rating
def __update_rating(uid, rating): ''' Update the rating for post. ''' entry = TabPost.update( rating=rating ).where(TabPost.uid == uid) entry.execute()
python
def __update_rating(uid, rating): ''' Update the rating for post. ''' entry = TabPost.update( rating=rating ).where(TabPost.uid == uid) entry.execute()
Update the rating for post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_model.py#L87-L94
bukun/TorCMS
torcms/model/post_model.py
MPost.__update_kind
def __update_kind(uid, kind): ''' update the kind of post. ''' entry = TabPost.update( kind=kind, ).where(TabPost.uid == uid) entry.execute() return True
python
def __update_kind(uid, kind): ''' update the kind of post. ''' entry = TabPost.update( kind=kind, ).where(TabPost.uid == uid) entry.execute() return True
update the kind of post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_model.py#L97-L106
bukun/TorCMS
torcms/model/post_model.py
MPost.update_cnt
def update_cnt(uid, post_data): ''' update content. ''' entry = TabPost.update( cnt_html=tools.markdown2html(post_data['cnt_md']), user_name=post_data['user_name'], cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md'].strip()), time_update=tools.timestamp() ).where(TabPost.uid == uid) entry.execute()
python
def update_cnt(uid, post_data): ''' update content. ''' entry = TabPost.update( cnt_html=tools.markdown2html(post_data['cnt_md']), user_name=post_data['user_name'], cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md'].strip()), time_update=tools.timestamp() ).where(TabPost.uid == uid) entry.execute()
update content.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_model.py#L117-L128
bukun/TorCMS
torcms/model/post_model.py
MPost.update_order
def update_order(uid, order): ''' Update the order of the posts. ''' entry = TabPost.update( order=order ).where(TabPost.uid == uid) entry.execute()
python
def update_order(uid, order): ''' Update the order of the posts. ''' entry = TabPost.update( order=order ).where(TabPost.uid == uid) entry.execute()
Update the order of the posts.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_model.py#L131-L138
bukun/TorCMS
torcms/model/post_model.py
MPost.update
def update(uid, post_data, update_time=False): ''' update the infor. ''' title = post_data['title'].strip() if len(title) < 2: return False cnt_html = tools.markdown2html(post_data['cnt_md']) try: if update_time: entry2 = TabPost.update( date=datetime.now(), time_create=tools.timestamp() ).where(TabPost.uid == uid) entry2.execute() except: pass cur_rec = MPost.get_by_uid(uid) entry = TabPost.update( title=title, user_name=post_data['user_name'], cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md'].strip()), memo=post_data['memo'] if 'memo' in post_data else '', cnt_html=cnt_html, logo=post_data['logo'], order=post_data['order'] if 'order' in post_data else '', keywords=post_data['keywords'] if 'keywords' in post_data else '', kind=post_data['kind'] if 'kind' in post_data else 1, extinfo=post_data['extinfo'] if 'extinfo' in post_data else cur_rec.extinfo, time_update=tools.timestamp(), valid=post_data.get('valid', 1) ).where(TabPost.uid == uid) entry.execute()
python
def update(uid, post_data, update_time=False): ''' update the infor. ''' title = post_data['title'].strip() if len(title) < 2: return False cnt_html = tools.markdown2html(post_data['cnt_md']) try: if update_time: entry2 = TabPost.update( date=datetime.now(), time_create=tools.timestamp() ).where(TabPost.uid == uid) entry2.execute() except: pass cur_rec = MPost.get_by_uid(uid) entry = TabPost.update( title=title, user_name=post_data['user_name'], cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md'].strip()), memo=post_data['memo'] if 'memo' in post_data else '', cnt_html=cnt_html, logo=post_data['logo'], order=post_data['order'] if 'order' in post_data else '', keywords=post_data['keywords'] if 'keywords' in post_data else '', kind=post_data['kind'] if 'kind' in post_data else 1, extinfo=post_data['extinfo'] if 'extinfo' in post_data else cur_rec.extinfo, time_update=tools.timestamp(), valid=post_data.get('valid', 1) ).where(TabPost.uid == uid) entry.execute()
update the infor.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_model.py#L141-L175
bukun/TorCMS
torcms/model/post_model.py
MPost.add_or_update
def add_or_update(uid, post_data): ''' Add or update the post. ''' cur_rec = MPost.get_by_uid(uid) if cur_rec: MPost.update(uid, post_data) else: MPost.create_post(uid, post_data)
python
def add_or_update(uid, post_data): ''' Add or update the post. ''' cur_rec = MPost.get_by_uid(uid) if cur_rec: MPost.update(uid, post_data) else: MPost.create_post(uid, post_data)
Add or update the post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_model.py#L178-L186
bukun/TorCMS
torcms/model/post_model.py
MPost.create_post
def create_post(post_uid, post_data): ''' create the post. ''' title = post_data['title'].strip() if len(title) < 2: return False cur_rec = MPost.get_by_uid(post_uid) if cur_rec: return False entry = TabPost.create( title=title, date=datetime.now(), cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md'].strip()), cnt_html=tools.markdown2html(post_data['cnt_md']), uid=post_uid, time_create=post_data.get('time_create', tools.timestamp()), time_update=post_data.get('time_update', tools.timestamp()), user_name=post_data['user_name'], view_count=post_data['view_count'] if 'view_count' in post_data else 1, logo=post_data['logo'], memo=post_data['memo'] if 'memo' in post_data else '', order=post_data['order'] if 'order' in post_data else '', keywords=post_data['keywords'] if 'keywords' in post_data else '', extinfo=post_data['extinfo'] if 'extinfo' in post_data else {}, kind=post_data['kind'] if 'kind' in post_data else '1', valid=post_data.get('valid', 1) ) return entry.uid
python
def create_post(post_uid, post_data): ''' create the post. ''' title = post_data['title'].strip() if len(title) < 2: return False cur_rec = MPost.get_by_uid(post_uid) if cur_rec: return False entry = TabPost.create( title=title, date=datetime.now(), cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md'].strip()), cnt_html=tools.markdown2html(post_data['cnt_md']), uid=post_uid, time_create=post_data.get('time_create', tools.timestamp()), time_update=post_data.get('time_update', tools.timestamp()), user_name=post_data['user_name'], view_count=post_data['view_count'] if 'view_count' in post_data else 1, logo=post_data['logo'], memo=post_data['memo'] if 'memo' in post_data else '', order=post_data['order'] if 'order' in post_data else '', keywords=post_data['keywords'] if 'keywords' in post_data else '', extinfo=post_data['extinfo'] if 'extinfo' in post_data else {}, kind=post_data['kind'] if 'kind' in post_data else '1', valid=post_data.get('valid', 1) ) return entry.uid
create the post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_model.py#L189-L220
bukun/TorCMS
torcms/model/post_model.py
MPost.query_cat_random
def query_cat_random(catid, **kwargs): ''' Get random lists of certain category. ''' num = kwargs.get('limit', 8) if catid == '': rand_recs = TabPost.select().order_by(peewee.fn.Random()).limit(num) else: rand_recs = TabPost.select().join( TabPost2Tag, on=(TabPost.uid == TabPost2Tag.post_id) ).where( (TabPost.valid == 1) & (TabPost2Tag.tag_id == catid) ).order_by( peewee.fn.Random() ).limit(num) return rand_recs
python
def query_cat_random(catid, **kwargs): ''' Get random lists of certain category. ''' num = kwargs.get('limit', 8) if catid == '': rand_recs = TabPost.select().order_by(peewee.fn.Random()).limit(num) else: rand_recs = TabPost.select().join( TabPost2Tag, on=(TabPost.uid == TabPost2Tag.post_id) ).where( (TabPost.valid == 1) & (TabPost2Tag.tag_id == catid) ).order_by( peewee.fn.Random() ).limit(num) return rand_recs
Get random lists of certain category.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_model.py#L223-L239
bukun/TorCMS
torcms/model/post_model.py
MPost.query_random
def query_random(**kwargs): ''' Return the random records of centain kind. ''' if 'limit' in kwargs: limit = kwargs['limit'] elif 'num' in kwargs: limit = kwargs['num'] else: limit = 10 kind = kwargs.get('kind', None) if kind: rand_recs = TabPost.select().where( (TabPost.kind == kind) & (TabPost.valid == 1) ).order_by( peewee.fn.Random() ).limit(limit) else: rand_recs = TabPost.select().where( TabPost.valid == 1 ).order_by( peewee.fn.Random() ).limit(limit) return rand_recs
python
def query_random(**kwargs): ''' Return the random records of centain kind. ''' if 'limit' in kwargs: limit = kwargs['limit'] elif 'num' in kwargs: limit = kwargs['num'] else: limit = 10 kind = kwargs.get('kind', None) if kind: rand_recs = TabPost.select().where( (TabPost.kind == kind) & (TabPost.valid == 1) ).order_by( peewee.fn.Random() ).limit(limit) else: rand_recs = TabPost.select().where( TabPost.valid == 1 ).order_by( peewee.fn.Random() ).limit(limit) return rand_recs
Return the random records of centain kind.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_model.py#L242-L269