本文整理汇总了Python中models.Conference.put方法的典型用法代码示例。如果您正苦于以下问题:Python Conference.put方法的具体用法?Python Conference.put怎么用?Python Conference.put使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.Conference
的用法示例。
在下文中一共展示了Conference.put方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_getSessionsBySpeaker
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def test_getSessionsBySpeaker(self):
# Create two conferences
conf = Conference(name='Test Conference A')
wckA = conf.put()
wckAsafe = wckA.urlsafe()
conf = Conference(name='Test Conference B')
wckB = conf.put()
wckBsafe = wckB.urlsafe()
# Add 4 sessions among conferences with three having particular speaker
propsA = {'name': 'Monkey Business', 'date': date(2015,8,8),
'parent': wckA, 'conferenceKey': wckAsafe,
'typeOfSession': 'lecture', 'startTime': time(18,15)}
propsB = {'name': 'Monkey Business', 'date': date(2015,9,12),
'parent': wckB, 'conferenceKey': wckBsafe,
'typeOfSession': 'workshop', 'startTime': time(12,15)}
# Add two to first created conference
Session(speaker=['Sarah', 'Frodo'], **propsA).put()
Session(speaker=['Frodo'], **propsA).put()
# Add two to second created conference
Session(speaker=['Saruman'], **propsB).put()
Session(speaker=['Gollum', 'Frodo'], **propsB).put()
# Test the endpoint
url = '/speaker/{0}'.format('Frodo')
res = urlfetch.fetch(self.urlbase + url)
self.assertEqual(res.status_code, 200)
self.assertEqual(len(json.loads(res.content)['items']), 3)
示例2: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def _createConferenceObject(self, conferenceForm):
"""Create conference object, returns ConferenceForm."""
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
data = formToDict(conferenceForm, exclude=('websafeKey', 'organizerDisplayName'))
# add default values for those missing
for df in DEFAULTS:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
# add organizerUserId before checking the required fields
data['organizerUserId'] = user_id = getUserId(user)
# check required fields
for key in Conference.required_fields_schema:
if not data[key]:
raise endpoints.BadRequestException("Conference '%s' field required" % key)
# convert dates from strings to Date objects; set month based on start_date
try:
data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()
data['endDate'] = datetime.strptime(data['endDate'][:10], "%Y-%m-%d").date()
except (TypeError, ValueError):
raise endpoints.BadRequestException("Invalid date format. Please use 'YYYY-MM-DD'")
if data['startDate'] > data['endDate']:
raise endpoints.BadRequestException("start date must be before end date")
data['month'] = data['startDate'].month
# set seatsAvailable to be same as maxAttendees on creation
if data["maxAttendees"] > 0:
data["seatsAvailable"] = data["maxAttendees"]
# generate Profile Key based on user ID and Conference
# ID based on Profile key get Conference key from ID
p_key = ndb.Key(Profile, user_id)
c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
c_key = ndb.Key(Conference, c_id, parent=p_key)
data['key'] = c_key
# create Conference, send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
conf = Conference(**data)
conf.put()
taskqueue.add(
params={'email': user.email(), 'conferenceInfo': repr(conferenceForm)},
url='/tasks/send_confirmation_email'
)
return conf.toForm()
示例3: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def _createConferenceObject(self, request):
"""Create or update Conference object, returning ConferenceForm/request."""
# preload necessary data items
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
if not request.name:
raise endpoints.BadRequestException("Conference 'name' field required")
# copy ConferenceForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
del data['websafeKey']
del data['organizerDisplayName']
# add default values for those missing (both data model & outbound Message)
for df in DEFAULTS:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
setattr(request, df, DEFAULTS[df])
# convert dates from strings to Date objects; set month based on start_date
if data['startDate']:
data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()
data['month'] = data['startDate'].month
else:
data['month'] = 0
if data['endDate']:
data['endDate'] = datetime.strptime(data['endDate'][:10], "%Y-%m-%d").date()
# set seatsAvailable to be same as maxAttendees on creation
# both for data model & outbound Message
if data["maxAttendees"] > 0:
data["seatsAvailable"] = data["maxAttendees"]
setattr(request, "seatsAvailable", data["maxAttendees"])
# make Profile Key from user ID
p_key = ndb.Key(Profile, user_id)
# allocate new Conference ID with Profile key as parent
c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
# make Conference key from ID
c_key = ndb.Key(Conference, c_id, parent=p_key)
data['key'] = c_key
data['organizerUserId'] = request.organizerUserId = user_id
# create Conference & return (modified) ConferenceForm
conference = Conference(**data)
conference.put()
return request
示例4: test_createSession
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def test_createSession(self):
test_url = '/conference/{wcksafe}/session'
# Ensure default profile is created
url = '/profile'
res = urlfetch.fetch(self.urlbase + url, method='GET')
self.assertEqual(res.status_code, 200)
# Create conference and get websafe key
conf = Conference(
name='Test Conference',
organizerUserId=json.loads(res.content)['mainEmail']
)
wck = conf.put()
sleep(0.1)
wcksafe = wck.urlsafe()
test_url = test_url.format(wcksafe=wcksafe)
# Ensure no sessions exist yet
self.assertEqual(0, len(Session.query().fetch(5)))
# Test endpoint
params = {
'name': 'TEST Session',
'date': '2015-8-10',
'startTime': '9:10',
'conferenceKey': wcksafe
}
response = urlfetch.fetch(self.urlbase + test_url,
payload=json.dumps(params),
method=urlfetch.POST,
headers={'Content-Type': 'application/json'})
self.assertEqual(response.status_code, 200)
示例5: new_conference
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def new_conference():
form = ConferenceForm()
if request.method == "POST" and form.validate_on_submit():
conference = Conference(
organizer=users.get_current_user().email()
)
form.populate_obj(conference)
try:
conference.put()
conference_id = conference.key.id()
flash(u'Conference %s successfully saved.' % conference_id, 'success')
return redirect(url_for('list_conferences'))
except CapabilityDisabledError:
flash(u'App Engine Datastore is currently in read-only mode.', 'info')
return redirect(url_for('list_conferences'))
logging.info('Form errors: %s' % form.errors)
return render_template('new_conference.html', form=form)
示例6: post
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def post(self, confid=''):
user = users.get_current_user()
if not user:
login_url = users.create_login_url('/')
self.redirect(login_url)
return
# check if the user is admin
if not users.is_current_user_admin():
self.response.out.write("You are not authorized")
return
# get conference
if not confid:
confid = self.request.get('id')
conference = Conference.get_by_id(confid)
if not conference:
conference = Conference(id=confid)
# update fields of the conference
conference.name = self.request.get('name')
conference.subtitle = self.request.get('subtitle')
conference.reviewers = self.request.get('reviewers').split()
# put the changes conference element
conference.put()
# redirect to the get page
self.redirect(self.request.url)
示例7: test_getConferenceSessions
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def test_getConferenceSessions(self):
# Create conference and get websafe key
url = '/conference'
conf = Conference(name='Test Conference')
wck = conf.put()
wcksafe = wck.urlsafe()
# Add 4 sessions
props = {'name': 'Monkey Business', 'date': date(2015,8,8),
'parent': wck, 'conferenceKey': wcksafe}
Session(typeOfSession='workshop', startTime=time(10,15), **props).put()
Session(typeOfSession='meetup', startTime=time(15,15), **props).put()
Session(typeOfSession='social', startTime=time(19,15), **props).put()
# Verify total conferences
url = '/conference/{0}/session'.format(wcksafe)
res = urlfetch.fetch(self.urlbase + url)
self.assertEqual(res.status_code, 200)
self.assertEqual(len(json.loads(res.content)['items']), 3)
示例8: test_getQuerySolution
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def test_getQuerySolution(self):
# Create conference and get websafe key
url = '/conference'
conf = Conference(name='Test Conference')
wck = conf.put()
wcksafe = wck.urlsafe()
# Add 4 sessions with 2 that will pass filter
props = {'name': 'Monkey Business', 'date': date(2015,8,8),
'parent': wck, 'conferenceKey': wcksafe}
Session(typeOfSession='workshop', startTime=time(10,15), **props).put()
Session(typeOfSession='meetup', startTime=time(15,15), **props).put()
Session(typeOfSession='flash', startTime=time(18,15), **props).put()
Session(typeOfSession='social', startTime=time(19,15), **props).put()
# Test the special query
url = '/conference/{0}/typeandtime'.format(wcksafe)
res = urlfetch.fetch(self.urlbase + url)
self.assertEqual(res.status_code, 200)
self.assertEqual(len(json.loads(res.content)['items']), 2)
示例9: test_getFeaturedSpeaker
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def test_getFeaturedSpeaker(self):
test_url = '/conference/featuredspeaker?websafeConferenceKey={wcksafe}'
sess_url = '/conference/{wcksafe}/session'
# Ensure default profile is created
url = '/profile'
res = urlfetch.fetch(self.urlbase + url, method='GET')
self.assertEqual(res.status_code, 200)
# Create conference and get websafe key
conf = Conference(
name='Test Conference',
organizerUserId=json.loads(res.content)['mainEmail']
)
wck = conf.put()
wcksafe = wck.urlsafe()
test_url = test_url.format(wcksafe=wcksafe)
sess_url = sess_url.format(wcksafe=wcksafe)
# Add a session with speaker
props = {'name': 'Monkey Business', 'date': '2015-8-8',
'conferenceKey': wcksafe,
'typeOfSession': 'lecture', 'startTime': '18:00',
'speaker': ['Sarah Baggins', 'Frodo Baggins']}
response = urlfetch.fetch(self.urlbase + sess_url,
payload=json.dumps(props),
method=urlfetch.POST,
headers={'Content-Type': 'application/json'})
self.assertEqual(response.status_code, 200)
# Test endpoint
res = urlfetch.fetch(self.urlbase + test_url)
self.assertEqual(res.status_code, 200)
self.assertEqual(json.loads(res.content)['data'], '')
# Add a second session with the previous speaker
props = {'name': 'Bull Business', 'date': '2015-8-8',
'conferenceKey': wcksafe,
'typeOfSession': 'lecture', 'startTime': '11:15',
'speaker': ['Frodo Baggins']}
response = urlfetch.fetch(self.urlbase + sess_url,
payload=json.dumps(props),
method=urlfetch.POST,
headers={'Content-Type': 'application/json'})
self.assertEqual(response.status_code, 200)
# Test endpoint again
res = urlfetch.fetch(self.urlbase + test_url)
self.assertEqual(res.status_code, 200)
self.assertEqual(json.loads(res.content)['data'], 'Frodo Baggins')
示例10: test_getConferenceSessionsBySpeaker
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def test_getConferenceSessionsBySpeaker(self):
# Create conference and get websafe key
conf = Conference(name='Test Conference')
wck = conf.put()
wcksafe = wck.urlsafe()
# Add 4 sessions with speakers
props = {'name': 'Monkey Business', 'date': date(2015,8,8),
'parent': wck, 'conferenceKey': wcksafe,
'typeOfSession': 'lecture', 'startTime': time(18,15)}
Session(speaker=['Sarah Baggins', 'Frodo Baggins'], **props).put()
Session(speaker=['Frodo Baggins'], **props).put()
Session(speaker=['Saruman'], **props).put()
Session(speaker=['Gollum', 'Legolas'], **props).put()
# Test the endpoint
url = '/conference/{0}/speaker/{1}'.format(
wcksafe, 'Frodo%20Baggins'
)
res = urlfetch.fetch(self.urlbase + url)
self.assertEqual(res.status_code, 200)
self.assertEqual(len(json.loads(res.content)['items']), 2)
示例11: test_getConferenceSessionsByType
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def test_getConferenceSessionsByType(self):
# Create conference and get websafe key
conf = Conference(name='Test Conference')
wck = conf.put()
wcksafe = wck.urlsafe()
# Add 4 sessions with speakers
props = {'name': 'Monkey Business', 'date': date(2015,8,8),
'parent': wck, 'conferenceKey': wcksafe,
'startTime': time(18,15)}
Session(typeOfSession='lecture', **props).put()
Session(typeOfSession='workshop', **props).put()
Session(typeOfSession='gathering', **props).put()
Session(typeOfSession='lecture', **props).put()
# Test the endpoint
url = '/conference/{0}/sessiontype/{1}'.format(
wcksafe, 'lecture'
)
res = urlfetch.fetch(self.urlbase + url)
self.assertEqual(res.status_code, 200)
self.assertEqual(len(json.loads(res.content)['items']), 2)
示例12: test_addSessionToWishlist
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def test_addSessionToWishlist(self):
# Check that no profiles exist in datastore
prof = Profile.query().get()
self.assertEqual(prof, None)
# Create conference and get websafe key
conf = Conference(name='Test_conference')
wck = conf.put()
# Add a session
props = {'name': 'Monkey Business', 'date': date(2015,8,8),
'parent': wck, 'conferenceKey': wck.urlsafe(),
'typeOfSession': 'lecture', 'startTime': time(18,15)}
sk = Session(speaker=['Sarah', 'Frodo'], **props).put()
# Test the endpoint (This also creates a Profile record)
url = '/wishlist/{0}'.format(sk.urlsafe())
res = urlfetch.fetch(self.urlbase + url, method='POST')
self.assertEqual(res.status_code, 200)
self.assertTrue(json.loads(res.content)['data'])
sleep(0.1)
# Get profile and check for one session key
prof = Profile.query().get()
self.assertEqual(len(prof.sessionKeysToAttend), 1)
示例13: test_getSessionsInWishlist
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def test_getSessionsInWishlist(self):
# Create conference and get websafe key
conf = Conference(name='Test_conference')
wck = conf.put()
# Add a session
props = {'name': 'Monkey Business', 'date': date(2015,8,8),
'parent': wck, 'conferenceKey': wck.urlsafe(),
'typeOfSession': 'lecture', 'startTime': time(18,15)}
sk = Session(speaker=['Sarah', 'Frodo'], **props).put()
# Have endpoint create default Profile record
res = urlfetch.fetch(self.urlbase + '/profile')
self.assertEqual(res.status_code, 200)
sleep(0.1)
# Create profile with session key in wishlist
profile = Profile.query().get()
profile.sessionKeysToAttend = [sk.urlsafe()]
profile.put()
# Test the endpoint
url = '/wishlist/{0}'.format(wck.urlsafe())
res = urlfetch.fetch(self.urlbase + url, method='GET')
self.assertEqual(res.status_code, 200)
# Test if one entry in returned items list
self.assertEqual(len(json.loads(res.content)['items']), 1)
示例14: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def _createConferenceObject(self, request):
"""Create or update Conference object, returning
ConferenceForm/request."""
# preload necessary data items
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
if not request.name:
raise endpoints.BadRequestException(
"Conference 'name' field required")
# copy ConferenceForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name)
for field in request.all_fields()}
del data['websafeKey']
del data['organizerDisplayName']
# add default values for those missing
# (both data model & outbound Message)
for df in DEFAULTS:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
setattr(request, df, DEFAULTS[df])
# convert dates from strings to Date objects;
# set month based on start_date
if data['startDate']:
data['startDate'] = datetime.strptime(
data['startDate'][:10], "%Y-%m-%d"
).date()
data['month'] = data['startDate'].month
else:
data['month'] = 0
if data['endDate']:
data['endDate'] = datetime.strptime(
data['endDate'][:10], "%Y-%m-%d"
).date()
# set seatsAvailable to be same as maxAttendees on creation
if data["maxAttendees"] > 0:
data["seatsAvailable"] = data["maxAttendees"]
# generate Profile Key based on user ID and Conference
# ID based on Profile key get Conference key from ID
p_key = ndb.Key(Profile, user_id)
c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
c_key = ndb.Key(Conference, c_id, parent=p_key)
data['key'] = c_key
data['organizerUserId'] = request.organizerUserId = user_id
# create Conference, send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
conf = Conference(**data)
conf.put()
taskqueue.add(
params={
'email': user.email(),
'conferenceInfo': repr(request)},
url='/tasks/send_confirmation_email'
)
return self._copyConferenceToForm(conf, request.organizerDisplayName)
示例15: post
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import put [as 别名]
def post(self):
if not self.user.administrator:
return webapp2.redirect("/")
mode = self.request.POST["mode"]
if mode == "0":
# Institution
institution = Institution(name=self.request.POST["name"], website=self.request.POST["website"])
institution.put()
elif mode == "1":
thumbnail_url = self.request.POST["thumbnail"]
try:
content = urllib2.urlopen(thumbnail_url)
image = content.read()
except urllib2.HTTPError:
logging.warning("URL: " + thumbnail_url + "was not found.")
image = ""
institution = ndb.Key(urlsafe=self.request.POST["institution"])
author = Author(
name=self.request.POST["name"],
website=self.request.POST["website"],
thumbnail=image,
institution=institution,
)
author.put()
elif mode == "2":
# Conference
conference = Conference(name=self.request.POST["name"], acronym=self.request.POST["acronym"])
conference.put()
pass
elif mode == "3":
# Publication
date = datetime.strptime(self.request.POST["date"], "%Y-%m-%d")
# A bit messy, does author order
authors = self.request.params.getall("authors")
idx = 0
author_order = [int(order_idx) for order_idx in self.request.POST["order"].split(",")]
ordered_authors = []
for author_idx in range(len(authors)):
ordered_authors.append(ndb.Key(urlsafe=authors[author_order[author_idx] - 1]))
conference = ndb.Key(urlsafe=self.request.POST["conference"])
pdf_image_url = self.request.POST["pdfimage"]
image = ""
if pdf_image_url:
try:
content = urllib2.urlopen(pdf_image_url)
image = content.read()
except urllib2.HTTPError:
logging.warning("URL: " + pdf_image_url + "was not found.")
publication = Publication(
title=self.request.POST["title"],
abstract=self.request.POST["abstract"],
date=date,
authors=ordered_authors,
citation=self.request.POST["citation"],
conference=conference,
pdf=self.request.POST["pdf"],
pdf_image=image,
arxiv_link=self.request.POST["arxiv"],
project_page=self.request.POST["projectpage"],
)
publication.put()
elif mode == "4":
# Content
content = Content(name=self.request.POST["name"], content=self.request.POST["content"])
content.put()
elif mode == "5":
# Project
authors = []
for author in self.request.params.getall("authors"):
authors.append(ndb.Key(urlsafe=author))
image_url = self.request.POST["image"]
if image_url:
try:
content = urllib2.urlopen(image_url)
image = content.read()
except urllib2.HTTPError:
logging.warning("URL: " + image_url + "was not found.")
image = ""
else:
image = ""
publications = []
for publication in self.request.params.getall("publications"):
publications.append(ndb.Key(urlsafe=publication))
contents = []
for content in self.request.params.getall("contents"):
contents.append(ndb.Key(urlsafe=content))
tags = []
for tag in self.request.POST["tags"].split(","):
#.........这里部分代码省略.........