本文整理汇总了Python中pyramid_sqlalchemy.Session.add方法的典型用法代码示例。如果您正苦于以下问题:Python Session.add方法的具体用法?Python Session.add怎么用?Python Session.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid_sqlalchemy.Session
的用法示例。
在下文中一共展示了Session.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_view_via_post
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def add_view_via_post(request):
import os, shutil
from pkg_resources import resource_filename
from pyramid_sqlalchemy import Session
from pyramid.httpexceptions import HTTPFound
from ..forms import NewStudentForm
from ..models import NewStudentModel
form = NewStudentForm(request.POST)
# 該欄位是文字欄位,可省略不輸入,但我們希望在這情況下塞到資料庫是 NULL,所以這邊強制改成 None
if form.signup_number.data == '': form.signup_number.data = None
if form.validate():
new_student = NewStudentModel()
form.populate_obj(new_student)
if form.picture.data:
# 有上傳大頭照,要存檔,並將資料庫對應的欄位設定
picture_name = form.id_number.data + os.path.splitext(form.picture.data.filename)[-1]
with open(resource_filename('tp_enroll', 'static/pictures/{}'.format(picture_name)), 'wb') as output:
shutil.copyfileobj(form.picture.data.file, output)
new_student.picture_name = picture_name
# 觸發 auto increment
new_student.id = None
# 鄰的欄位,應該要純數字。如果使用者誤填了鄰,要刪掉多餘的文字
if new_student.neighborhood.endswith('鄰'):
new_student.neighborhood = new_student.neighborhood[:-1]
Session.add(new_student)
return HTTPFound(location=request.route_path('home'))
return {'form': form}
示例2: __setitem__
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def __setitem__(self, key, node):
node.name = str(key)
if self.id is None:
Session.flush()
node.parent_id = self.id
Session.add(node)
Session.flush()
示例3: test_applications_list_apps_one_app
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def test_applications_list_apps_one_app(self):
user = User(screen_name='John Doe',
first_name='John',
last_name='Doe',
email='[email protected]')
app = Application(name='Test Application',
main_url='https://example.com',
callback_url='https://example.com/callback',
production_ready=False)
user.applications.append(app)
with transaction.manager:
Session.add(user)
Session.flush()
app_id = app.id
user_id = user.id
self.testapp.get('/__login/' + str(user_id))
res = self.testapp.get('/oauth2/applications')
self.assertEqual(res.status, '200 OK')
res.mustcontain('John')
res.mustcontain('Log out')
res.mustcontain('Developer Applications')
res.mustcontain('Register new application')
res.mustcontain(app_id)
res.mustcontain('Test Application')
res.mustcontain('https://example.com')
示例4: test_password_delete_found
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def test_password_delete_found(self):
password = Password(service='myservice',
secret='s3cr3t',
user_id=self.user_id)
with transaction.manager:
Session.add(password)
Session.flush()
password_id = password.id
count_before = Session.query(Password).count()
self.assertEqual(count_before, 1)
res = self.testapp.delete('/passwords/%s' % str(password_id),
headers=self.auth_header)
self.assertEqual(res.status, '200 OK')
self.assertEqual(res.body, (b'{"password": {"id": "'
+ text_type(password_id).encode('ascii')
+ b'"}}'))
count_after = Session.query(Password).count()
self.assertEqual(count_after, 0)
try:
password = Session.query(Password).filter(
Password.id == password_id
).one()
except NoResultFound:
password = None
self.assertEqual(password, None)
示例5: test_backups_export_some_passwords
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def test_backups_export_some_passwords(self):
user_id = create_and_login_user(self.testapp)
with freeze_time('2012-12-12 12:12:12'):
password1 = Password(secret='secret1', user_id=user_id)
password2 = Password(secret='secret2', user_id=user_id)
with transaction.manager:
Session.add(password1)
Session.add(password2)
Session.flush()
with freeze_time('2012-01-10'):
res = self.testapp.get('/backup/export')
self.assertEqual(res.status, '200 OK')
self.assertEqual(res.content_type, 'application/yith-library')
uncompressedData = self.getUncompressData(res.body)
self.assertEqual(json.loads(uncompressedData), [
{"account": "", "service": "", "tags": [], "notes": "",
"creation": "2012-12-12T12:12:12", "secret": "secret1",
"expiration": None, "modification": "2012-12-12T12:12:12"},
{"account": "", "service": "", "tags": [], "notes": "",
"creation": "2012-12-12T12:12:12", "secret": "secret2",
"expiration": None, "modification": "2012-12-12T12:12:12"},
])
self.assertEqual(
res.content_disposition,
'attachment; filename=yith-library-backup-2012-01-10.yith',
)
示例6: main
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
with transaction.manager:
model = User(name=u'admin', password=u'admin')
DBSession.add(model)
from jinja2.utils import generate_lorem_ipsum
for id, article in enumerate(range(100), start=1):
title = generate_lorem_ipsum(
n=1, # Одно предложение
html=False, # В виде обычного текста
min=2, # Минимум 2 слова
max=5 # Максимум 5
)
content = generate_lorem_ipsum()
article = Article(**{'title': title, 'content': content})
DBSession.add(article)
示例7: collection_timestamp
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def collection_timestamp(self, collection_id, parent_id, auth=None):
"""Get the highest timestamp of every objects in this `collection_id` for
this `parent_id`.
.. note::
This should take deleted objects into account.
:param str collection_id: the collection id.
:param str parent_id: the collection parent.
:returns: the latest timestamp of the collection.
:rtype: int
"""
tb = Timestamps.__table__
qry = select([label('last_modified', func.max(tb.c.last_modified))]).where(and_(
tb.c.parent_id == parent_id,
tb.c.collection_id == collection_id))
last_modified, = Session.execute(qry).fetchone()
if last_modified is None:
last_modified = datetime.datetime.utcnow()
with transaction.manager:
Session.add(Timestamps(parent_id=parent_id, collection_id=collection_id,
last_modified=last_modified))
return last_modified.replace(tzinfo=datetime.timezone.utc).timestamp()
示例8: test_application_edit_unauthorized
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def test_application_edit_unauthorized(self):
create_and_login_user(self.testapp)
app = Application(name='Test Application',
main_url='http://example.com',
callback_url='http://example.com/callback',
authorized_origins=['http://example.com',
'https://example.com'],
production_ready=False,
image_url='http://example.com/image.png',
description='example description')
other_user = User(screen_name='Alice doe',
first_name='Alice',
last_name='Doe',
email='[email protected]')
other_user.applications.append(app)
with transaction.manager:
Session.add(other_user)
Session.flush()
app_id = app.id
res = self.testapp.get('/oauth2/applications/%s/edit' % str(app_id),
status=401)
self.assertEqual(res.status, '401 Unauthorized')
示例9: preferences
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def preferences(request):
schema = UserPreferencesSchema()
button1 = Button('submit', _('Save changes'))
button1.css_class = 'btn-primary'
form = Form(schema, buttons=(button1, ))
user = request.user
if 'submit' in request.POST:
controls = request.POST.items()
try:
appstruct = form.validate(controls)
except ValidationFailure as e:
return {'form': e.render()}
user.update_preferences(appstruct)
Session.add(user)
request.session.flash(
_('The changes were saved successfully'),
'success',
)
return HTTPFound(location=request.route_path('user_preferences'))
return {
'form': form.render({
'allow_google_analytics': user.allow_google_analytics,
'send_passwords_periodically': user.send_passwords_periodically,
})
}
示例10: handle_refresh_token
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def handle_refresh_token(request, client):
if 'refresh_token' not in request.POST:
log.info('refresh_token field missing')
return HTTPBadRequest(InvalidRequest(error_description='refresh_token '
'field required'))
if 'user_id' not in request.POST:
log.info('user_id field missing')
return HTTPBadRequest(InvalidRequest(error_description='user_id '
'field required'))
auth_token = db.query(Oauth2Token).filter_by(
refresh_token=request.POST.get('refresh_token')).first()
if not auth_token:
log.info('invalid refresh_token')
return HTTPUnauthorized(InvalidToken(error_description='Provided '
'refresh_token is not valid.'))
if auth_token.client.client_id != client.client_id:
log.info('invalid client_id')
return HTTPBadRequest(InvalidClient(error_description='Client does '
'not own this refresh_token.'))
if str(auth_token.user_id) != request.POST.get('user_id'):
log.info('invalid user_id')
return HTTPBadRequest(InvalidClient(error_description='The given '
'user_id does not match the given refresh_token.'))
new_token = auth_token.refresh()
db.add(new_token)
db.flush()
return new_token.asJSON(token_type='bearer')
示例11: test_application_edit_invalid_change
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def test_application_edit_invalid_change(self):
user = User(screen_name='John Doe',
first_name='John',
last_name='Doe',
email='[email protected]')
app = Application(name='Test Application',
main_url='http://example.com',
callback_url='http://example.com/callback',
authorized_origins=['http://example.com',
'https://example.com'],
production_ready=False,
image_url='http://example.com/image.png',
description='example description')
user.applications.append(app)
with transaction.manager:
Session.add(user)
Session.flush()
app_id = app.id
user_id = user.id
self.testapp.get('/__login/' + str(user_id))
res = self.testapp.post('/oauth2/applications/%s/edit' % str(app_id), {
'submit': 'Save changes',
})
self.assertEqual(res.status, '200 OK')
res.mustcontain('There was a problem with your submission')
res.mustcontain('Required')
示例12: test_application_edit_cancel
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def test_application_edit_cancel(self):
user = User(screen_name='John Doe',
first_name='John',
last_name='Doe',
email='[email protected]')
app = Application(name='Test Application',
main_url='http://example.com',
callback_url='http://example.com/callback',
authorized_origins=['http://example.com',
'https://example.com'],
production_ready=False,
image_url='http://example.com/image.png',
description='example description')
user.applications.append(app)
with transaction.manager:
Session.add(user)
Session.flush()
app_id = app.id
user_id = user.id
self.testapp.get('/__login/' + str(user_id))
res = self.testapp.post('/oauth2/applications/%s/edit' % str(app_id), {
'cancel': 'Cancel',
})
self.assertEqual(res.status, '302 Found')
self.assertEqual(res.location, 'http://localhost/oauth2/applications')
示例13: put
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def put(self):
try:
uuid.UUID(self.password_id)
except ValueError:
return invalid_password_id()
password = self._get_password()
if password is None:
return password_not_found()
else:
cleaned_data, errors = validate_password(self.request.body,
self.request.charset)
if errors:
result = {'message': ','.join(errors)}
return HTTPBadRequest(body=json.dumps(result),
charset='utf8',
content_type='application/json')
password.secret = cleaned_data['secret']
password.service = cleaned_data['service']
password.account = cleaned_data['account']
password.expiration = cleaned_data['expiration']
password.notes = cleaned_data['notes']
password.tags = cleaned_data['tags']
Session.add(password)
return {'password': password.as_dict()}
示例14: verify_email
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def verify_email(request):
try:
code = request.params['code']
except KeyError:
return HTTPBadRequest('Missing code parameter')
try:
email = request.params['email']
except KeyError:
return HTTPBadRequest('Missing email parameter')
evc = EmailVerificationCode(code)
user = evc.verify(email)
if user is not None:
request.session.flash(
_('Congratulations, your email has been successfully verified'),
'success',
)
user.verify_email()
Session.add(user)
return {
'verified': True,
}
else:
request.session.flash(
_('Sorry, your verification code is not correct or has expired'),
'error',
)
return {
'verified': False,
}
示例15: test_clients_two_apps
# 需要导入模块: from pyramid_sqlalchemy import Session [as 别名]
# 或者: from pyramid_sqlalchemy.Session import add [as 别名]
def test_clients_two_apps(self):
administrator = User(screen_name='Alice doe',
first_name='Alice',
last_name='Doe',
email='[email protected]')
app1 = Application(name='Example app 1',
main_url='https://example.com',
callback_url='https://example.com/callback',
image_url='https://example.com/image.png',
description='example description',
production_ready=True,
user=administrator)
app2 = Application(name='Example app 2',
main_url='https://2.example.com',
callback_url='https://2.example.com/callback',
production_ready=False,
user=administrator)
with transaction.manager:
Session.add(app1)
Session.add(app2)
Session.flush()
res = self.testapp.get('/oauth2/clients')
self.assertEqual(res.status, '200 OK')
res.mustcontain(
'Available Clients', 'Example app 1', 'https://example.com',
'https://example.com/image.png', 'example description',
no=('Example app 2', 'https://2.example.com'),
)