code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
'''
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
|
def delete_by_user_name(user_name)
|
Delete user in the database by `user_name`.
| 4.231161 | 3.4666 | 1.220551 |
'''
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
|
def delete(user_id)
|
Delele the user in the database by `user_id`.
| 5.901251 | 3.502033 | 1.685093 |
'''
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))
|
def gen_post_map(file_name, ext_url='')
|
Generate the urls for posts.
:return: None
| 4.659058 | 3.961854 | 1.175979 |
'''
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))
|
def gen_wiki_map(file_name, ext_url='')
|
Generate the urls for wiki.
:return: None
| 3.042925 | 2.734894 | 1.11263 |
'''
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)
|
def run_sitemap(_)
|
Generate the sitemap file.
:param args: args
:return: None
| 3.897916 | 3.41174 | 1.142501 |
'''
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')
|
def run_editmap(_)
|
Generate the urls file for editing.
:param args: args
:return: None
| 4.76021 | 3.750182 | 1.269328 |
'''
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
|
def get_meta(catid, sig)
|
Get metadata of dataset via ID.
| 5.580027 | 5.279693 | 1.056885 |
'''
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)
|
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.
| 3.761338 | 3.395042 | 1.107891 |
'''
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)
|
def update_label(signature, post_data)
|
Update the label when updating.
| 3.832212 | 3.506691 | 1.092828 |
'''
The default page of POST.
'''
self.render('post_{0}/post_index.html'.format(self.kind),
userinfo=self.userinfo,
kwd={'uid': '', })
|
def index(self)
|
The default page of POST.
| 17.432436 | 9.323946 | 1.869641 |
'''
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
|
def _gen_uid(self)
|
Generate the ID for post.
:return: the new ID.
| 7.662562 | 4.486291 | 1.707995 |
'''
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
|
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.
| 4.853715 | 3.061646 | 1.585329 |
'''
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)
|
def _to_add_with_category(self, catid)
|
Used for info2.
:param catid: the uid of category
| 5.354309 | 4.118379 | 1.300101 |
'''
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()
|
def _view_or_add(self, uid)
|
Try to get the post. If not, to add the wiki.
| 7.932034 | 4.343462 | 1.826201 |
'''
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, })
|
def _to_add(self, **kwargs)
|
Used for info1.
| 5.778893 | 4.89182 | 1.181338 |
'''
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()
)
|
def _to_edit(self, infoid)
|
render the HTML page for post editing.
| 3.73189 | 3.579218 | 1.042655 |
'''
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)
|
def _gen_last_current_relation(self, post_id)
|
Generate the relation for the post and last post viewed.
| 3.231098 | 2.549365 | 1.267413 |
'''
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)
|
def redirect_kind(self, postinfo)
|
Redirect according the kind of the post.
:param postinfo: the postinfo
:return: None
| 6.174779 | 4.667446 | 1.322946 |
'''
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)
|
def viewinfo(self, postinfo)
|
In infor.
| 4.692673 | 4.564913 | 1.027987 |
'''
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
|
def _the_view_kwd(self, postinfo)
|
Generate the kwd dict for view.
:param postinfo: the postinfo
:return: dict
| 6.31526 | 5.354963 | 1.179328 |
'''
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
|
def fetch_additional_posts(self, uid)
|
fetch the rel_recs, and random recs when view the post.
| 4.213413 | 3.186529 | 1.322258 |
'''
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
|
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.
| 3.736472 | 2.651968 | 1.408943 |
'''
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)
|
def fetch_post_data(self)
|
fetch post accessed data. post_data, and ext_dic.
| 4.177336 | 3.09427 | 1.350023 |
'''
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))
|
def add(self, **kwargs)
|
in infor.
| 4.57488 | 4.443582 | 1.029548 |
'''
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))
|
def update(self, uid)
|
in infor.
| 4.768541 | 4.668727 | 1.021379 |
'''
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))
|
def _delete(self, *args, **kwargs)
|
delete the post.
| 5.015236 | 4.739066 | 1.058275 |
'''
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)
|
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.
| 5.243207 | 2.590023 | 2.024387 |
'''
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)
|
def _to_edit_kind(self, post_uid)
|
Show the page for changing the category.
| 7.208519 | 5.933138 | 1.214959 |
'''
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))
|
def _change_kind(self, post_uid)
|
To modify the category of the post, and kind.
| 6.809023 | 5.141751 | 1.324262 |
'''
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)
|
def list(self, cur_p='')
|
Lists of the entities.
| 4.768538 | 4.147997 | 1.1496 |
'''
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
|
def down(self, down_uid)
|
Download the entity by UID.
| 7.131328 | 6.382057 | 1.117403 |
'''
To add the entity.
'''
kwd = {
'pager': '',
}
self.render('misc/entity/entity_add.html',
cfg=config.CMS_CFG,
kwd=kwd,
userinfo=self.userinfo)
|
def to_add(self)
|
To add the entity.
| 11.052478 | 8.291032 | 1.333064 |
'''
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)
|
def add_entity(self)
|
Add the entity. All the information got from the post data.
| 3.049761 | 2.167531 | 1.407021 |
'''
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)
|
def add_pic(self, post_data)
|
Adding the picture.
| 2.994818 | 2.91574 | 1.027121 |
'''
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)
|
def add_pdf(self, post_data)
|
Adding the pdf file.
| 3.78924 | 3.633313 | 1.042916 |
'''
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)
|
def add_url(self, post_data)
|
Adding the URL as entity.
| 4.878012 | 4.249803 | 1.147821 |
'''
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)
|
def p_changepassword(self)
|
Changing password.
| 5.484508 | 5.171918 | 1.06044 |
'''
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)
|
def p_changeinfo(self)
|
Change Infor via Ajax.
| 8.146511 | 6.367929 | 1.279303 |
'''
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)
|
def fetch_post_data(self)
|
fetch post accessed data. post_data, and ext_dic.
| 4.276234 | 2.720114 | 1.572079 |
'''
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
|
def __check_valid(self, post_data)
|
To check if the user is succesfully created.
Return the status code dict.
| 2.243061 | 1.801118 | 1.245371 |
'''
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)
|
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.
| 4.168939 | 2.364059 | 1.763467 |
'''
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
|
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.
| 4.819852 | 2.960843 | 1.627865 |
'''
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
|
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.
| 4.952671 | 3.079068 | 1.608497 |
'''
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))
|
def login(self)
|
user login.
| 3.213739 | 3.149952 | 1.02025 |
'''
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)
|
def p_to_find(self, )
|
To find, pager.
| 13.673448 | 8.78847 | 1.555839 |
'''
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)
|
def find(self, keyword=None, cur_p='')
|
find by keyword.
| 12.461843 | 11.821466 | 1.054171 |
'''
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
|
def reset_password(self)
|
Do reset password
:return:
| 3.693774 | 3.617055 | 1.02121 |
'''
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, )
|
def gen_passwd(self)
|
reseting password
| 3.077472 | 2.973366 | 1.035013 |
'''
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')
|
def set_language(self, language)
|
Set the cookie for locale.
| 3.160412 | 2.449696 | 1.290124 |
'''
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
|
def gen_radio_view(sig_dic)
|
for checkbox
| 4.289013 | 4.175012 | 1.027306 |
'''
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
|
def gen_checkbox_view(sig_dic)
|
for checkbox
| 4.101243 | 4.116076 | 0.996396 |
'''
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)
|
def gen_select_view(sig_dic)
|
HTML view, for selection.
| 3.415179 | 3.2462 | 1.052054 |
'''
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
|
def gen_radio_list(sig_dic)
|
For generating List view HTML file for RADIO.
for each item.
| 7.509722 | 5.270314 | 1.42491 |
'''
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
|
def gen_checkbox_list(sig_dic)
|
For generating List view HTML file for CHECKBOX.
for each item.
| 7.532079 | 5.268412 | 1.429668 |
'''
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
|
def gen_select_list(sig_dic)
|
For generating List view HTML file for SELECT.
for each item.
| 5.795949 | 4.152918 | 1.395633 |
'''
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
|
def gen_input_add(sig_dic)
|
Adding for HTML Input control.
| 3.002796 | 2.48388 | 1.208914 |
'''
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
|
def gen_input_edit(sig_dic)
|
Editing for HTML input control.
| 2.833171 | 2.462487 | 1.150532 |
'''
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
|
def gen_input_view(sig_dic)
|
Viewing the HTML text.
| 3.784822 | 3.368173 | 1.123702 |
'''
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
)
|
def gen_radio_add(sig_dic)
|
Adding for HTML radio control.
| 3.365309 | 3.081091 | 1.092246 |
'''
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
|
def gen_radio_edit(sig_dic)
|
editing for HTML radio control.
| 4.343089 | 3.973189 | 1.093099 |
'''
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
|
def gen_checkbox_add(sig_dic)
|
for checkbox
| 3.771204 | 3.761803 | 1.002499 |
'''
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
|
def gen_checkbox_edit(sig_dic)
|
for checkbox
| 4.50124 | 4.506307 | 0.998875 |
'''
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)
|
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',
}
| 3.156662 | 1.8807 | 1.678451 |
'''
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)
|
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.
| 4.305668 | 2.604944 | 1.652883 |
'''
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)
|
def delete(uid)
|
Delete by uid
| 2.283807 | 2.243989 | 1.017744 |
'''
Update the rating for post.
'''
entry = TabPost.update(
rating=rating
).where(TabPost.uid == uid)
entry.execute()
|
def __update_rating(uid, rating)
|
Update the rating for post.
| 8.809587 | 6.060857 | 1.453522 |
'''
update the kind of post.
'''
entry = TabPost.update(
kind=kind,
).where(TabPost.uid == uid)
entry.execute()
return True
|
def __update_kind(uid, kind)
|
update the kind of post.
| 9.239129 | 6.567967 | 1.406695 |
'''
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()
|
def update_cnt(uid, post_data)
|
update content.
| 5.269962 | 4.799043 | 1.098128 |
'''
Update the order of the posts.
'''
entry = TabPost.update(
order=order
).where(TabPost.uid == uid)
entry.execute()
|
def update_order(uid, order)
|
Update the order of the posts.
| 8.904836 | 5.589653 | 1.593093 |
'''
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()
|
def update(uid, post_data, update_time=False)
|
update the infor.
| 3.095293 | 2.981533 | 1.038155 |
'''
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)
|
def add_or_update(uid, post_data)
|
Add or update the post.
| 3.847236 | 3.492551 | 1.101555 |
'''
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
|
def create_post(post_uid, post_data)
|
create the post.
| 2.722783 | 2.671168 | 1.019323 |
'''
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
|
def query_cat_random(catid, **kwargs)
|
Get random lists of certain category.
| 3.227605 | 2.902864 | 1.111869 |
'''
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
|
def query_random(**kwargs)
|
Return the random records of centain kind.
| 2.887928 | 2.223306 | 1.298934 |
'''
query recent posts.
'''
order_by_create = kwargs.get('order_by_create', False)
kind = kwargs.get('kind', None)
if order_by_create:
if kind:
recent_recs = TabPost.select().where(
(TabPost.kind == kind) & (TabPost.valid == 1)
).order_by(
TabPost.time_create.desc()
).limit(num)
else:
recent_recs = TabPost.select().where(
TabPost.valid == 1
).order_by(
TabPost.time_create.desc()
).limit(num)
else:
if kind:
recent_recs = TabPost.select().where(
(TabPost.kind == kind) & (TabPost.valid == 1)
).order_by(
TabPost.time_update.desc()
).limit(num)
else:
recent_recs = TabPost.select().where(
TabPost.valid == 1
).order_by(
TabPost.time_update.desc()
).limit(num)
return recent_recs
|
def query_recent(num=8, **kwargs)
|
query recent posts.
| 1.691724 | 1.648201 | 1.026406 |
'''
query all the posts.
'''
kind = kwargs.get('kind', '1')
limit = kwargs.get('limit', 10)
return TabPost.select().where(
(TabPost.kind == kind) &
(TabPost.valid == 1)
).order_by(
TabPost.time_update.desc()
).limit(limit)
|
def query_all(**kwargs)
|
query all the posts.
| 3.935 | 3.368656 | 1.168122 |
'''
Query keywords, empty.
'''
return TabPost.select().where((TabPost.kind == kind) & (TabPost.keywords == ''))
|
def query_keywords_empty(kind='1')
|
Query keywords, empty.
| 8.691638 | 5.913408 | 1.469819 |
'''
Query posts recently update.
'''
return TabPost.select().where(
(TabPost.kind == kind) &
(TabPost.time_update > timstamp)
).order_by(
TabPost.time_update.desc()
)
|
def query_recent_edited(timstamp, kind='1')
|
Query posts recently update.
| 4.846052 | 3.498 | 1.385378 |
'''
Query posts, outdate.
'''
return TabPost.select().where(
TabPost.kind == kind
).order_by(
TabPost.time_update.asc()
).limit(num)
|
def query_dated(num=8, kind='1')
|
Query posts, outdate.
| 8.605485 | 4.857514 | 1.771582 |
'''
Query most pics.
'''
return TabPost.select().where(
(TabPost.kind == kind) & (TabPost.logo != "")
).order_by(TabPost.view_count.desc()).limit(num)
|
def query_most_pic(num, kind='1')
|
Query most pics.
| 5.986784 | 4.911252 | 1.218993 |
'''
Query recent posts of catalog.
'''
if label:
recent_recs = MPost.query_cat_recent_with_label(
cat_id,
label=label,
num=num,
kind=kind,
order=order
)
else:
recent_recs = MPost.query_cat_recent_no_label(
cat_id,
num=num,
kind=kind,
order=order
)
return recent_recs
|
def query_cat_recent(cat_id, label=None, num=8, kind='1', order=False)
|
Query recent posts of catalog.
| 2.579736 | 2.30475 | 1.119313 |
'''
Query recent posts of catalog.
'''
return TabPost.select().join(
TabPost2Tag,
on=(TabPost.uid == TabPost2Tag.post_id)
).where(
(TabPost.kind == kind) &
(TabPost2Tag.tag_id == cat_id)
).order_by(
TabPost.time_create.desc()
)
|
def query_by_tag(cat_id, kind='1')
|
Query recent posts of catalog.
| 3.908338 | 3.081942 | 1.268141 |
'''
query_cat_recent_with_label
'''
if order:
sort_criteria = TabPost.order.asc()
else:
sort_criteria = TabPost.time_create.desc()
return TabPost.select().join(
TabPost2Tag,
on=(TabPost.uid == TabPost2Tag.post_id)
).where(
(TabPost.kind == kind) &
(TabPost2Tag.tag_id == cat_id) &
(TabPost.extinfo['def_tag_arr'].contains(label))
).order_by(
sort_criteria
).limit(num)
|
def query_cat_recent_with_label(cat_id, label=None, num=8, kind='1', order=False)
|
query_cat_recent_with_label
| 3.454373 | 3.42056 | 1.009885 |
'''
:param cat_id_arr: list of categories. ['0101', '0102']
:param label: the additional label
'''
if label:
return MPost.__query_with_label(
cat_id_arr,
label=label,
num=num,
kind=kind
)
return MPost.query_total_cat_recent_no_label(cat_id_arr, num=num, kind=kind)
|
def query_total_cat_recent(cat_id_arr, label=None, num=8, kind='1')
|
:param cat_id_arr: list of categories. ['0101', '0102']
:param label: the additional label
| 4.135617 | 2.760714 | 1.498024 |
'''
:param cat_id_arr: list of categories. ['0101', '0102']
'''
return TabPost.select().join(
TabPost2Tag,
on=(TabPost.uid == TabPost2Tag.post_id)
).where(
(TabPost.kind == kind) &
(TabPost2Tag.tag_id << cat_id_arr) & # the "<<" operator signifies an "IN" query
(TabPost.extinfo['def_tag_arr'].contains(label))
).order_by(
TabPost.time_create.desc()
).limit(num)
|
def __query_with_label(cat_id_arr, label=None, num=8, kind='1')
|
:param cat_id_arr: list of categories. ['0101', '0102']
| 4.814704 | 3.849869 | 1.250615 |
'''
:param cat_id_arr: list of categories. ['0101', '0102']
'''
return TabPost.select().join(
TabPost2Tag,
on=(TabPost.uid == TabPost2Tag.post_id)
).where(
(TabPost.kind == kind) &
(TabPost2Tag.tag_id << cat_id_arr) # the "<<" operator signifies an "IN" query
).order_by(
TabPost.time_create.desc()
).limit(num)
|
def query_total_cat_recent_no_label(cat_id_arr, num=8, kind='1')
|
:param cat_id_arr: list of categories. ['0101', '0102']
| 4.297693 | 3.300534 | 1.30212 |
'''
Query most viewed.
'''
return TabPost.select().where(
(TabPost.kind == kind) &
(TabPost.valid == 1)
).order_by(
TabPost.view_count.desc()
).limit(num)
|
def query_most(num=8, kind='1')
|
Query most viewed.
| 4.423387 | 3.55074 | 1.245765 |
'''
update rating, kind, or count
'''
if 'rating' in kwargs:
MPost.__update_rating(uid, kwargs['rating'])
elif 'kind' in kwargs:
MPost.__update_kind(uid, kwargs['kind'])
elif 'keywords' in kwargs:
MPost.__update_keywords(uid, kwargs['keywords'])
elif 'count' in kwargs:
MPost.__update_view_count(uid)
|
def update_misc(uid, **kwargs)
|
update rating, kind, or count
| 3.51822 | 2.631382 | 1.337024 |
'''
Update with keywords.
'''
entry = TabPost.update(keywords=inkeywords).where(TabPost.uid == uid)
entry.execute()
|
def __update_keywords(uid, inkeywords)
|
Update with keywords.
| 11.593722 | 7.493248 | 1.547223 |
'''
Get next record by time_create.
'''
current_rec = MPost.get_by_uid(in_uid)
recs = TabPost.select().where(
(TabPost.kind == kind) &
(TabPost.time_create < current_rec.time_create)
).order_by(TabPost.time_create.desc())
if recs.count():
return recs.get()
return None
|
def get_next_record(in_uid, kind='1')
|
Get next record by time_create.
| 3.754994 | 2.980591 | 1.259815 |
'''
Get All the records.
'''
return TabPost.select().where(
(TabPost.kind == kind) &
(TabPost.valid == 1)
).order_by(
TabPost.time_update.desc()
)
|
def get_all(kind='2')
|
Get All the records.
| 5.414061 | 4.141427 | 1.307294 |
'''
Update the json.
'''
cur_extinfo = MPost.get_by_uid(uid).extinfo
for key in extinfo:
cur_extinfo[key] = extinfo[key]
entry = TabPost.update(
extinfo=cur_extinfo,
).where(TabPost.uid == uid)
entry.execute()
return uid
|
def update_jsonb(uid, extinfo)
|
Update the json.
| 4.760877 | 4.233115 | 1.124675 |
'''
update meta of the rec.
'''
if extinfo is None:
extinfo = {}
title = data_dic['title'].strip()
if len(title) < 2:
return False
cur_info = MPost.get_by_uid(uid)
if cur_info:
# ToDo: should not do this. Not for 's'
if DB_CFG['kind'] == 's':
entry = TabPost.update(
title=title,
user_name=data_dic['user_name'],
keywords='',
time_update=tools.timestamp(),
date=datetime.now(),
cnt_md=data_dic['cnt_md'],
memo=data_dic['memo'] if 'memo' in data_dic else '',
logo=data_dic['logo'],
order=data_dic['order'],
cnt_html=tools.markdown2html(data_dic['cnt_md']),
valid=data_dic['valid']
).where(TabPost.uid == uid)
entry.execute()
else:
cur_extinfo = cur_info.extinfo
# Update the extinfo, Not replace
for key in extinfo:
cur_extinfo[key] = extinfo[key]
entry = TabPost.update(
title=title,
user_name=data_dic['user_name'],
keywords='',
time_update=tools.timestamp(),
date=datetime.now(),
cnt_md=data_dic['cnt_md'],
memo=data_dic['memo'] if 'memo' in data_dic else '',
logo=data_dic['logo'],
order=data_dic['order'] if 'order' in data_dic else '',
cnt_html=tools.markdown2html(data_dic['cnt_md']),
extinfo=cur_extinfo,
valid=data_dic['valid']
).where(TabPost.uid == uid)
entry.execute()
else:
return MPost.add_meta(uid, data_dic, extinfo)
return uid
|
def modify_meta(uid, data_dic, extinfo=None)
|
update meta of the rec.
| 2.716053 | 2.642753 | 1.027736 |
'''
update when init.
'''
postinfo = MPost.get_by_uid(uid)
entry = TabPost.update(
time_update=tools.timestamp(),
date=datetime.now(),
kind=data_dic['kind'] if 'kind' in data_dic else postinfo.kind,
keywords=data_dic['keywords'] if 'keywords' in data_dic else postinfo.keywords,
).where(TabPost.uid == uid)
entry.execute()
return uid
|
def modify_init(uid, data_dic)
|
update when init.
| 4.879082 | 4.341226 | 1.123895 |
'''
Get All data of certain kind according to the condition
'''
if DB_CFG['kind'] == 's':
return TabPost.select().where(
(TabPost.kind == kind) & (TabPost.valid == 1)
).order_by(
TabPost.time_update.desc()
)
return TabPost.select().where(
(TabPost.kind == kind) &
(TabPost.valid == 1) &
TabPost.extinfo.contains(condition)
).order_by(TabPost.time_update.desc())
|
def query_under_condition(condition, kind='2')
|
Get All data of certain kind according to the condition
| 3.791455 | 3.213892 | 1.179708 |
'''
Get records of certain pager.
'''
all_list = MPost.query_under_condition(con, kind=kind)
return all_list[(idx - 1) * CMS_CFG['list_num']: idx * CMS_CFG['list_num']]
|
def query_list_pager(con, idx, kind='2')
|
Get records of certain pager.
| 10.100516 | 6.746055 | 1.497248 |
'''
Get the count of certain kind.
'''
recs = TabPost.select().where(TabPost.kind == kind)
return recs.count()
|
def count_of_certain_kind(kind)
|
Get the count of certain kind.
| 9.988093 | 6.726747 | 1.484833 |
'''
Query pager
'''
return TabPost.select().where(TabPost.kind == kind).order_by(
TabPost.time_create.desc()
).paginate(
current_page_num, CMS_CFG['list_num']
)
|
def query_pager_by_slug(kind, current_page_num=1)
|
Query pager
| 6.054306 | 5.64895 | 1.071758 |
'''
excel中的数据作为表中的字段,创建表
'''
XLSX_FILE = './database/esheet/20180811.xlsx'
if os.path.exists(XLSX_FILE):
pass
else:
return
fields = []
for sheet_ranges in load_workbook(filename=XLSX_FILE):
for xr in FILTER_COLUMNS:
row1_val = sheet_ranges[xr + "1"].value
row2_val = sheet_ranges[xr + "2"].value
row3_val = sheet_ranges[xr + "3"].value
row4_val = sheet_ranges[xr + "4"].value
if row1_val and row1_val.strip() != '':
desc = {
'slug': row1_val,
'name': row2_val,
'type': row3_val,
'display_mode': row4_val
}
fields.append(desc)
create_tab(fields)
|
def gen_xlsx_table()
|
excel中的数据作为表中的字段,创建表
| 4.360447 | 3.687213 | 1.182586 |
'''
In infor.
'''
self.redirect_kind(postinfo)
if DB_CFG['kind'] == 's':
cat_enum1 = []
else:
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
cat_enum1 = MCategory.get_qian2(ext_catid2[:2]) if ext_catid else []
catinfo = None
p_catinfo = None
post2catinfo = MPost2Catalog.get_first_category(postinfo.uid)
catalog_infors = None
if post2catinfo:
catinfo = MCategory.get_by_uid(post2catinfo.tag_id)
if catinfo:
p_catinfo = MCategory.get_by_uid(catinfo.pid)
catalog_infors = MPost2Catalog.query_pager_by_slug(catinfo.slug,
current_page_num=1,
order=True)
kwd = self._the_view_kwd(postinfo)
MPost.update_misc(postinfo.uid, count=True)
if self.get_current_user():
MUsage.add_or_update(self.userinfo.uid, postinfo.uid, postinfo.kind)
tmpl = 'post_{0}/leaf_view.html'.format(self.kind)
logger.info('The Info Template: {0}'.format(tmpl))
self.render(tmpl,
kwd=dict(kwd, **self.ext_view_kwd(postinfo)),
postinfo=postinfo,
userinfo=self.userinfo,
catinfo=catinfo,
pcatinfo=p_catinfo,
ad_switch=random.randint(1, 18),
tag_info=MPost2Label.get_by_uid(postinfo.uid),
catalog_infos=catalog_infors,
cat_enum=cat_enum1)
|
def viewinfo(self, postinfo)
|
In infor.
| 4.812173 | 4.63818 | 1.037513 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.