本文整理汇总了Python中flask.g.db方法的典型用法代码示例。如果您正苦于以下问题:Python g.db方法的具体用法?Python g.db怎么用?Python g.db使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.g
的用法示例。
在下文中一共展示了g.db方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_protobuf_in_db
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def update_protobuf_in_db(table_name, msg, id):
try:
# If protobuf has an id field and it's uint64, make it a string
id_field = msg.DESCRIPTOR.fields_by_name['id']
if id_field.type == id_field.TYPE_UINT64:
id = str(id)
except AttributeError:
pass
cur = g.db.cursor()
msg_dict = protobuf_to_dict(msg, type_callable_map=type_callable_map)
columns = ', '.join(list(msg_dict.keys()))
placeholders = ':'+', :'.join(list(msg_dict.keys()))
setters = ', '.join('{}=:{}'.format(key, key) for key in msg_dict)
query = 'UPDATE %s SET %s WHERE id=%s' % (table_name, setters, id)
cur.execute(query, msg_dict)
g.db.commit()
示例2: api_profiles_activities
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def api_profiles_activities(player_id):
if request.method == 'POST':
if not request.stream:
return '', 400
activity = activity_pb2.Activity()
activity.ParseFromString(request.stream.read())
activity.id = get_id('activity')
insert_protobuf_into_db('activity', activity)
return '{"id": %ld}' % activity.id, 200
# request.method == 'GET'
activities = activity_pb2.Activities()
cur = g.db.cursor()
# Select every column except 'fit' - despite being a blob python 3 treats it like a utf-8 string and tries to decode it
cur.execute("SELECT id, player_id, f3, name, f5, f6, start_date, end_date, distance, avg_heart_rate, max_heart_rate, avg_watts, max_watts, avg_cadence, max_cadence, avg_speed, max_speed, calories, total_elevation, strava_upload_id, strava_activity_id, f23, fit_filename, f29, date FROM activity WHERE player_id = ?", (str(player_id),))
for row in cur.fetchall():
activity = activities.activities.add()
row_to_protobuf(row, activity, exclude_fields=['fit'])
return activities.SerializeToString(), 200
# For ghosts
示例3: setUp
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def setUp(self):
# Init db
self.engine, self.Session = models.get_working_db_for_tests()
self.db = self.Session()
self.db.begin()
# Flask
self.app = app = Flask(__name__)
app.debug = app.testing = True
app.json_encoder = DynamicJSONEncoder
app.test_client_class = FlaskJsonClient
ArticleView.route_as_view(app, 'articles', ('/article/', '/article/<int:id>'))
GirlWatcherView.route_as_view(app, 'girlwatchers', ('/girlwatcher/', '/girlwatcher/<int:id>'))
@app.before_request
def db():
g.db = self.db
示例4: test_delete
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def test_delete(self):
""" Test delete() """
# Delete
with self.app.test_client() as c:
rv = c.delete('/article/10', json=None)
art = rv['article']
art.pop('comments', None)
self.assertEqual(rv['article'], {
'id': 10, 'uid': 1,
'title': '10',
'theme': None,
'data': {'o': {'a': True}, 'rating': 5},
})
self.db.close()
self.assertRaises(NoResultFound, c.get, '/article/10') # really removed
示例5: sql_query
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def sql_query(keyword):
if not hasattr(g, 'db'):
g.db = MySQLdb.connect(
host = conf.db_host,
port = conf.db_port,
user = conf.db_user,
passwd = conf.db_passwd,
db = conf.db_name,
charset = 'utf8')
c = g.db.cursor()
sql = '''select title, type, answer from `erya` where title like %s limit 30'''
c.execute(sql, ('%' + unicode(keyword) + '%', ))
result = [dict(title = it[0], type = it[1], answer = it[2]) for it in c.fetchall()]
return result
############################################################
示例6: get
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def get(self, project_name):
if g.token and g.token["type"] == "user":
project = g.db.execute_one_dict('''
SELECT p.id, p.name, p.type, p.public, co.role AS userrole
FROM project p
LEFT JOIN collaborator co ON p.id = co.project_id AND co.user_id = %s
WHERE p.name = %s
''', [g.token["user"]["id"], project_name])
else:
project = g.db.execute_one_dict('''
SELECT id, name, type, public
FROM project
WHERE name = %s
''', [project_name])
if not project:
abort(404)
return project
示例7: before_request
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def before_request():
def release_db():
db = getattr(g, 'db', None)
if not db:
return
dbpool.put(db)
g.db = None
g.release_db = release_db
g.db = dbpool.get()
if app.config['OPA_ENABLED']:
g.token = normalize_token(get_token())
check_request_authorization()
示例8: check_job_belongs_to_project
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def check_job_belongs_to_project(f):
@wraps(f)
def decorated_function(*args, **kwargs):
project_id = kwargs.get('project_id')
job_id = kwargs.get('job_id')
assert project_id
assert job_id
r = g.db.execute_one('''
SELECT id
FROM job
WHERE id = %s AND project_id = %s
''', [job_id, project_id])
if not r:
logger.debug('job does not belong to project')
abort(404)
return f(*args, **kwargs)
return decorated_function
示例9: enrich_job_token
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def enrich_job_token(token):
if not ("job" in token and "id" in token["job"] and validate_uuid(token["job"]["id"])):
raise LookupError('invalid job id')
job_id = token["job"]["id"]
r = g.db.execute_one('''
SELECT state, project_id, name
FROM job
WHERE id = %s''', [job_id])
if not r:
raise LookupError('job not found')
token['job']['state'] = r[0]
token['job']['name'] = r[2]
token['project'] = {}
token['project']['id'] = r[1]
return token
示例10: select_blogs_by_id_sql
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def select_blogs_by_id_sql(newsid):
c = g.db.cursor()
sql ="select * from blog where newsid =%s" %(newsid)
c.execute(sql)
results=c.fetchone()
index=results[0]
sql ="select * from blog where id< %d and id>%d" %(index,index-9)
c.execute(sql)
results=c.fetchall()
blogs=[]
blogjsonlist={}
for index in range(8) :
blogs.append(json.loads(results[7-index][2]))
blogjsonlist['nextId']=results[0][1]
blogjsonlist['newslist']=blogs
blogs=json.dumps(blogjsonlist).decode("unicode-escape")
return blogs
示例11: validate_job_token
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def validate_job_token(token):
job_id = token['job']['id']
r = g.db.execute_one('''
SELECT state, project_id, name
FROM job
WHERE id = %s''', [job_id])
if not r:
logger.warn('job not found')
abort(401, 'Unauthorized')
job_state = r[0]
if job_state not in ('queued', 'running', 'scheduled'):
logger.warn('job not in an active state')
abort(401, 'Unauthorized')
token['job']['state'] = r[0]
token['job']['name'] = r[2]
token['project'] = {}
token['project']['id'] = r[1]
g.token = token
示例12: test_remove_blocked_users
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def test_remove_blocked_users(self, mock_request):
"""
Check removing user from block list.
"""
self.create_user_with_role(
self.user.name, self.user.email, self.user.password, Role.admin)
with self.app.test_client() as c:
c.post("/account/login", data=self.create_login_form_data(self.user.email, self.user.password))
blocked_user = BlockedUsers(1, "Bad user")
g.db.add(blocked_user)
g.db.commit()
self.assertNotEqual(BlockedUsers.query.filter(BlockedUsers.comment == "Bad user").first(), None)
c.post("/blocked_users", data=dict(user_id=1, remove=True))
self.assertEqual(BlockedUsers.query.filter(BlockedUsers.user_id == 1).first(), None)
with c.session_transaction() as session:
flash_message = dict(session['_flashes']).get('message')
self.assertEqual(flash_message, "User removed successfully.")
示例13: test_webhook_release
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def test_webhook_release(self, mock_request):
"""
Check webhook release update CCExtractor Version for release.
"""
with self.app.test_client() as c:
# Full Release with version with 2.1
data = {'action': 'published',
'release': {'prerelease': False, 'published_at': '2018-05-30T20:18:44Z', 'tag_name': 'v2.1'}}
# one of ip address from GitHub web hook
last_commit = GeneralData.query.filter(GeneralData.key == 'last_commit').first()
# abcdefgh is the new commit after previous version defined in base.py
last_commit.value = 'abcdefgh'
g.db.commit()
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'release'))
last_release = CCExtractorVersion.query.order_by(CCExtractorVersion.released.desc()).first()
self.assertEqual(last_release.version, '2.1')
示例14: test_webhook_release_edited
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def test_webhook_release_edited(self, mock_request):
"""
Check webhook action "edited" updates the specified version.
"""
from datetime import datetime
with self.app.test_client() as c:
release = CCExtractorVersion('2.1', '2018-05-30T20:18:44Z', 'abcdefgh')
g.db.add(release)
g.db.commit()
# Full Release with version with 2.1
data = {'action': 'edited',
'release': {'prerelease': False, 'published_at': '2018-06-30T20:18:44Z', 'tag_name': 'v2.1'}}
last_commit = GeneralData.query.filter(GeneralData.key == 'last_commit').first()
# abcdefgh is the new commit after previous version defined in base.py
last_commit.value = 'abcdefgh'
g.db.commit()
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'release'))
last_release = CCExtractorVersion.query.filter_by(version='2.1').first()
self.assertEqual(last_release.released,
datetime.strptime('2018-06-30T20:18:44Z', '%Y-%m-%dT%H:%M:%SZ').date())
示例15: test_webhook_release_deleted
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import db [as 别名]
def test_webhook_release_deleted(self, mock_request):
"""
Check webhook action "delete" removes the specified version.
"""
with self.app.test_client() as c:
release = CCExtractorVersion('2.1', '2018-05-30T20:18:44Z', 'abcdefgh')
g.db.add(release)
g.db.commit()
# Delete full release with version with 2.1
data = {'action': 'deleted',
'release': {'prerelease': False, 'published_at': '2018-05-30T20:18:44Z', 'tag_name': 'v2.1'}}
last_commit = GeneralData.query.filter(GeneralData.key == 'last_commit').first()
# abcdefgh is the new commit after previous version defined in base.py
last_commit.value = 'abcdefgh'
g.db.commit()
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'release'))
last_release = CCExtractorVersion.query.order_by(CCExtractorVersion.released.desc()).first()
self.assertNotEqual(last_release.version, '2.1')