本文整理汇总了Python中site_helper.model函数的典型用法代码示例。如果您正苦于以下问题:Python model函数的具体用法?Python model怎么用?Python model使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了model函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_multi_delete
def test_multi_delete(self):
# reset tag model
decorator = [('Tag', dict(tag_model_name='Tag', data_key='tags', \
split_char=' ', auto_operate='reset'))]
model = sh.model('ForTestTag', decorator)
tag_model = sh.model('Tag')
# 插入一个数据
new_id_1 = model.insert(dict(title='python', tags='script'))
new_id_2 = model.insert(dict(title='c++', tags='compiled'))
# Tag表保存了相关数据
tag_items = tag_model.all()
self.assertEqual(len(tag_items), 2)
self.assertEqual(tag_items[0].name, 'script')
self.assertEqual(tag_items[1].name, 'compiled')
# 删除这个数据, Tag表中的数据也被删除
model.delete(new_id_1)
tag_items = tag_model.all()
self.assertEqual(len(tag_items), 1)
self.assertEqual(tag_items[0].name, 'compiled')
# 使用removeTag删除标签,Tag表中的数据也被删除
model.removeTag(new_id_2, 'compiled')
self.assertFalse(model.hasTag(new_id_2, 'compiled'))
self.assertEqual(tag_model.all(), [])
# 每个标签在Tag表中保存一个记录
model.insert(dict(title='shell', tags='power complex cool'))
self.assertEqual(len(tag_model.all()), 3)
示例2: POST
def POST(self, inputs=None):
if not inputs:
inputs = sh.inputs()
assert inputs.has_key("action")
if inputs.action == "postImage":
assert inputs.get("Userid", 0)
assert sh.model("User").get(inputs.Userid)
assert inputs.get("data_name", None)
assert inputs.get("data_id", None)
img_model = sh.model("UserImage")
image_data = sh.getSwfUploadImageFile()
new_id = img_model.insert(
sh.storage(
dict(
image_file=image_data,
Userid=inputs.Userid,
file_name=image_data.filename,
data_name=inputs.data_name,
data_id=inputs.data_id,
)
)
)
return "success;%d;%s;%s" % (new_id, img_model.getUrlByPrivate(inputs.Userid, new_id), image_data.filename)
示例3: __getattr__
def __getattr__(self, key):
db = DBHelper.DBHelper()
try:
if key == 'id': key = self._primary_key
return web.Storage.__getattr__(self, key)
except AttributeError:
key = key.replace('_', '') # 以方便item.abc_def替代item.abcdef
if ModelData.model_names.has_key(key):
model_name = ModelData.model_names[key]
table_name = model_name.rpartition('.')[2]
if self.has_key(table_name + 'id'):
try:
return sh.model(model_name).get(self.get(table_name + 'id'))
except:
print 'ERROR: ModelData找不到属性', key
raise
if key.endswith('s') and ModelData.model_names.has_key(key[:-1]):
model_name = ModelData.model_names[key[:-1]]
table_name = model_name.rpartition('.')[2]
id_key = self.get('_table_name') + 'id'
if db.isColumnExists(table_name, id_key):
try:
return sh.model(model_name).all({'where': [id_key + '=%s', self.id]})
except:
print 'ERROR: ModelData找不到属性', key
raise
raise
示例4: test_POST
def test_POST(self):
f_model = sh.model('UserForgetPassword')
my_id = self.register()
# 设置Userid后便可以删除
new_id = f_model.insert(dict(Userid=my_id, code='c'))
self.assertIsNotNone(f_model.get(new_id))
data = {'model_name': 'UserForgetPassword', 'model_id': new_id}
self.get(api_url, data)
self.assertIsNone(f_model.get(new_id))
# 删除不存在的数据会返回True,但是affected等于0
res = self.get(api_url, data)
res = sh.loadsJson(res)
self.assertTrue(res.success)
self.assertEqual(res.affected, 0)
# 如果没有登录的话,是不能删除的
data['model_id'] = f_model.insert(dict(Userid=my_id, code='c'))
self.logout()
res = self.get(api_url, data)
res = sh.loadsJson(res)
self.assertFalse(res.success)
# 不能删除别人的数据
my_id = self.register()
new_id = f_model.insert(dict(Userid=my_id+1, code='c'))
data['model_id'] = new_id
res = self.get(api_url, data)
res = sh.loadsJson(res)
self.assertFalse(res.success)
# 如果没有Userid属性的话,是不能删除的
s_model = sh.model('SiteConfig')
new_id = s_model.insert(dict(name='n', value='v'))
res = self.get(api_url, {'model_name': 'SiteConfig', 'model_id': new_id})
res = sh.loadsJson(res)
self.assertFalse(res.success)
self.assertIsNotNone(s_model.get(new_id))
示例5: _operateSetting
def _operateSetting(argv, usage, actions):
try:
assert len(argv) == 4 or len(argv) == 5
assert argv[1] in actions
if len(argv) == 4:
argv.append('')
action, email, key, value = argv[1:]
user_model = sh.model('User')
setting_model = sh.model('Setting')
user = user_model.getByEmail(email)
if not user:
print 'ERROR: user %s is not exists' % email
exit(0)
exists = setting_model.getOneByWhere('Userid=%s and type=%s', user.id, key)
if action == 'get':
if exists:
print exists.value
elif action == 'set':
if exists:
setting_model.update(exists.id, {'value': value})
else:
setting_model.insert({'Userid': user.id, 'type': key, 'value': value})
elif action == 'delete':
if exists:
setting_model.delete(exists.id)
except Exception:
print usage
示例6: GET
def GET(self):
inputs = sh.inputs()
assert inputs.has_key("code")
assert inputs.has_key("state")
site_name = inputs.state.partition("_")[0]
authorization_code = inputs.code.strip()
oauth_ctrl = sh.ctrl("oauth.%s" % site_name)
oauth_model = sh.model("oauth.%sOAuth2" % site_name)
user_ctrl = sh.ctrl("User")
user_model = sh.model("User")
token_url = oauth_ctrl.createAccessTokenUrl(authorization_code)
content = sh.requestHtmlContent(token_url, None, oauth_ctrl.ACCESS_TOKEN_METHOD)
assert content, u"第三方返回的数据有误"
access_token, access_expires = oauth_ctrl.pickAccessTokenAndExpires(content)
requested_uid = oauth_ctrl.requestUidWithAccessToken(access_token)
assert requested_uid, u"第三方返回的数据有误"
if self.TEST_API_LOGIN:
login_url = "%s/api/oauth/login?access_token=%s&access_expires=%s&uid=%s&state=%s" % (
sh.config.HOST_NAME,
access_token,
access_expires,
requested_uid,
inputs.state,
)
return '<a href="%s" >%s</a>' % (login_url, login_url)
# 因为access_token是动态变化的,所以要用requested_uid来判断是否登录过
# 这也避免了access_token变化时插入重复的uid
exists = oauth_model.getByUid(requested_uid)
# 如果当前uid还没有插入数据库,则先插入再考虑绑定Userid
if not exists:
new_oauth_id = oauth_model.insert(
dict(uid=requested_uid, access_token=access_token, access_expires=access_expires)
)
exists = oauth_model.get(new_oauth_id)
# 如果已绑定Userid则登录
if exists.Userid:
return self.login(exists.Userid)
# 如果希望自动注册,则注册并绑定后登录
if self.NO_REGISTER_ACTION == "auto_register":
data = oauth_ctrl.assignUserInfo(sh.storage(), access_token)
self.assignRandomPassword(data)
self.assignRegisterIP(data)
conflict = user_ctrl.checkNewUser(data)
if conflict:
return self.redirectToRegister(access_token, inputs.state, error=conflict)
new_user_id = user_model.insert(data)
oauth_model.update(exists.id, dict(Userid=new_user_id))
return self.login(new_user_id)
# 否则希望用户自己注册
elif self.NO_REGISTER_ACTION == "to_register":
return self.redirectToRegister(access_token, inputs.state)
示例7: _delete
def _delete(self, inputs=None):
assert(sh.session.is_admin)
if inputs is None: inputs = sh.inputs()
assert(inputs.has_key('model_name'))
assert(inputs.has_key('model_id'))
model = sh.model(inputs.model_name)
model.delete(int(inputs.model_id))
return sh.model(inputs.model_name).update(int(inputs.model_id),inputs)
示例8: login
def login(self, user, remember_me=False, ignore_cookie=False, inc_count=True):
sh.session.id = user.id
sh.session.is_login = True
sh.session.name = user.name
if remember_me and not ignore_cookie:
sh.setCookie('email', user.email)
sh.setCookie('md5password', user.password)
if user.has_key('login_count') and inc_count:
sh.model(self.model_name).update(user.id, {'login_count': user.login_count+1})
示例9: test_sh_model
def test_sh_model(self):
image_model2 = sh.model('Image')
self.assertIs(image_model2, image_model)
# 指明decorator参数时则不使用单例模式
decorator = [('Orderby', dict(orderby='{$primary_key} desc')),]
image_model3 = sh.model('Image', decorator)
self.assertIsNot(image_model3, image_model)
image_model4 = sh.model('Image', decorator)
self.assertIsNot(image_model4, image_model3)
# sh.model的decorator参数仅能用于测试环境
sh.config.IS_TEST = False
self.assertRaises(AssertionError, sh.model, 'Image', decorator)
sh.config.IS_TEST = True
示例10: GET
def GET(self):
inputs = sh.inputs()
assert(inputs.has_key('Userid'))
assert(inputs.has_key('code'))
model = sh.model('UserValidation')
exists = model.getOneByWhere('Userid=%s and code=%s', inputs.Userid, inputs.code)
if exists:
sh.model('User').update(inputs.Userid, dict(activated='yes'))
model.delete(exists.id)
return sh.alert('验证邮箱成功')
else:
return sh.redirectTo404()
示例11: test_delete_delete
def test_delete_delete(self):
decorator = [('Cascade', dict(
delete=[('Image', 'data_id'), ],
))]
# 插入一个user
id1 = sh.model('User').insert(test_user_data)
# 插入一张图片, 并关联data_id为Userid
image_data = {image_model.image_key: test_image_data, 'data_id': id1}
id2 = image_model.insert(image_data)
# 删除user
user_model = sh.model('User', decorator)
user_model.delete(id1)
# 图片数据也被删除
self.assertIsNone(image_model.get(id2))
示例12: test_multi
def test_multi(self):
model = sh.model("ForTestCategory")
# 插入ForTestCategory
new_id = model.insert(dict(title="python", cat="computer"))
item = model.get(new_id)
# 自动插入了Categoryid
self.assertIsNotNone(item.category)
self.assertEqual(item.category.name, "computer")
self.assertEqual(model.getCategory(new_id), "computer")
# 设置不存在的分类时抛出异常
self.assertRaises(AssertionError, model.setCategory, new_id, "psychics")
# 但可以通过addCategory添加一个新分类
model.addCategory("psychics")
self.assertEqual(model.getCategory(new_id), "computer")
# 然后用setCategory设置
model.setCategory(new_id, "psychics")
self.assertEqual(model.getCategory(new_id), "psychics")
# 用getAllCategory获得已有的两个分类
self.assertEqual(model.getAllCategory(), ["computer", "psychics"])
# 可用hasCategory判断是否已有某分类
self.assertTrue(model.hasCategory("computer"))
self.assertTrue(model.hasCategory("psychics"))
self.assertFalse(model.hasCategory("math"))
# addNewCategory也可以添加分类,但是不能已存在
model.addNewCategory("math")
self.assertTrue(model.hasCategory("math"))
self.assertRaises(AssertionError, model.addNewCategory, "math")
# 通过update可以自动设置新分类
model.update(new_id, dict(cat="language"))
self.assertEqual(model.getCategory(new_id), "language")
self.assertEqual(model.get(new_id).category.name, "language")
示例13: checkNewUser
def checkNewUser(self, data):
email = data.get('email', '').strip()
name = data.get('name', '').strip()
password = data.get('password', '')
model = sh.model(self.model_name)
if not re.match(r"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$", email):
return '请输入正确的邮箱地址'
if model.getByEmail(email):
return '此邮箱已注册'
if model.getByName(name):
return '此用户名已注册'
if not (4 <= len(name) <=30):
return '用户名必须大于等于4个字符,小于等于30个字符'
if not(6 <= len(password) <= 60):
return '密码必须大于等于6个字符,小于等于60个字符'
# 限制用户名字符
#if not re.match(r'^[a-zA-Z0-9_]+$', data.name.encode('utf-8')):
# return '用户名只能使用字母、数字、下划线'
return None
示例14: _operateSetting
def _operateSetting(argv, usage, actions):
try:
assert len(argv) == 3 or len(argv) == 4
assert argv[1] in actions
if len(argv) == 3:
argv.append('')
action, name, value = argv[1:]
model = sh.model('SiteConfig')
exists = model.getOneByWhere('name=%s', [name])
if action == 'get':
if exists:
print exists.value
elif action == 'set':
if exists:
model.update(exists.id, {'value': value})
else:
model.insert({'name': name, 'value': value})
elif action == 'delete':
if exists:
model.delete(exists.id)
except Exception:
print usage
示例15: assignUserInfo
def assignUserInfo(self, data, access_token):
new_data = sh.copy(data) if data else sh.storage()
exists = sh.model(self.MODEL_NAME).getByAccessToken(access_token)
if not exists: return new_data
res = sh.requestHtmlContent(self.USER_INFO_URL, (
'access_token', access_token,
'oauth_consumer_key', self.getAppID(),
'uid', exists.uid,
))
if not res: return new_data
res = sh.loadsJson(res)
if res.get('error_code', None): return new_data
if not new_data.has_key('name'):
new_data['name'] = res.screen_name
if res.gender == 'm':
new_data['sex'] = '他'
elif res.gender == 'f':
new_data['sex'] = '她'
else:
new_data['sex'] = '保密'
image_file = sh.requestImageFile(res.avatar_large)
if image_file:
new_data['image_file'] = image_file
return new_data