本文整理汇总了Python中models.Site类的典型用法代码示例。如果您正苦于以下问题:Python Site类的具体用法?Python Site怎么用?Python Site使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Site类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: delete
def delete(self, site_id = None):
site = Site.query.filter_by(id = site_id).first()
if site:
Site.delete(site.id)
return jsonify(ApiObjects(site.json()))
else:
return jsonify(ApiObjects())
开发者ID:Hackerfarm,项目名称:techrice,代码行数:7,代码来源:resources.py
示例2: getcurrentsite
def getcurrentsite(http_post, path_info, query_string):
""" Returns the site id and the page cache key based on the request.
"""
url = u'http://%s/%s' % (smart_unicode(http_post.rstrip('/')), \
smart_unicode(path_info.lstrip('/')))
pagecachekey = '%s?%s' % (smart_unicode(path_info), \
smart_unicode(query_string))
hostdict = hostcache_get()
if not hostdict:
hostdict = {}
if url not in hostdict:
default, ret = None, None
for site in Site.objects.all():
if url.startswith(site.url):
ret = site
break
if not default or site.default_site:
default = site
if not ret:
if default:
ret = default
else:
# Somebody is requesting something, but the user didn't create
# a site yet. Creating a default one...
ret = Site(name='Default Feedjack Site/Planet', \
url='www.feedjack.org', \
title='Feedjack Site Title', \
description='Feedjack Site Description. ' \
'Please change this in the admin interface.')
ret.save()
hostdict[url] = ret.id
hostcache_set(hostdict)
return hostdict[url], pagecachekey
开发者ID:weeyoung,项目名称:sentiment-analysis,代码行数:35,代码来源:fjlib.py
示例3: add_site
def add_site(self):
self.template_path = 'site_add.html'
# get the site code
site_code = self.request.get('site_code').strip()
self.vars['site_code'] = site_code
# return if there is no site_code, or we are not a post
if (not site_code) or self.request.method != 'POST' :
return
# check that the site_code is valid
if not Site.is_code_valid( site_code ):
self.vars['site_code_error'] = "site code is not valid"
return
# check that the site_code is valid
if Site.is_code_taken( site_code ):
self.vars['site_code_error'] = "site code already exists"
return
# ok to create
site = Site( site_code=site_code, owner=self.person )
site.put()
# create the first shared secret
SharedSecret.new_for_site( site )
self.redirect('/site/' + site_code )
开发者ID:evdb,项目名称:Privatar,代码行数:29,代码来源:site.py
示例4: register
def register(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password1']
domain = request.POST['domain']
print "=== User: ", username, " password: ", password, 'domain: ', domain
new_user = User.objects.create_user(username, '', password)
# create hash for new user
hasher = hashlib.md5()
hasher.update(username + domain)
h = hasher.hexdigest()
site = Site(user=new_user, hash=h, domain=domain)
site.save()
new_user.save()
return login_to_page(request, username, password)
else:
form = RegistrationForm()
return render_to_response(
'registration/registration_form.html',
{'form' : form},
context_instance=RC(request, {}),
)
开发者ID:kailu,项目名称:GrouponX,代码行数:26,代码来源:views.py
示例5: load_json_file
def load_json_file(filename):
site = Site()
rv = site.load_json(filename, True)
if rv is None:
print 'Error', filename
else :
print filename
开发者ID:JerryWorkman,项目名称:wvgeocoder,代码行数:7,代码来源:save_json.py
示例6: _create_example_site
def _create_example_site(user):
site = Site(
name='Example Site',
owner = user,
users = [user],
admins = [user],
example = True,
)
site.put()
for v in [4, 5]:
name = 'Html%d Example' % v
style = Style(site=site, name=name)
style.put()
rev = StyleRevision(parent=style, rev=0)
rev.put()
rev.update(render_template('examples/blog-html%d.css' % v))
style.published_rev = rev
rev = StyleRevision(parent=style, rev=1)
rev.put()
rev.update(render_template('examples/blog-html%d-preview.css' % v))
style.preview_rev = rev
style.put()
page = Page(site=site, name=name, url=url_for('example%d' % v, page_key=0, _external=True), _styles=[style.key()])
page.put()
page.url = url_for('example%d' % v, page_key=page.key(), _external=True)
page.put()
page.queue_refresh()
开发者ID:1ncnspcuous,项目名称:WebPutty,代码行数:28,代码来源:views.py
示例7: RetriveSongsBySite
def RetriveSongsBySite(site_name):
#if you dont pass anything in it gets all the sites
if site_name == '':
site = Site.all().fetch(150)
else:
site = Site.all().filter('name =', site_name).fetch(1)
return site
开发者ID:BenjaminDavison,项目名称:machinehype-gae,代码行数:8,代码来源:controllers.py
示例8: get_site
def get_site():
try:
site = Site.objects.get(name=EbaySpider.name)
except DoesNotExist as e:
logging.info(">>>> Creating site")
site = Site()
site.name = EbaySpider.name
return site
开发者ID:dlluncor,项目名称:simple-crawl,代码行数:9,代码来源:ebay.py
示例9: add_site
def add_site():
g.site = Site.get_by_hostname(request.host, app.config.get("DOMAIN_ROOT"))
if g.site is None:
if not app.config.get("DOMAIN_ROOT"):
return _("Config is missing a DOMAIN_ROOT: the domain name of your " "main site.")
if not app.config.get("ADMINS"):
return _("Config is missing ADMINS: used for login to your " "first site and recipient of error messages.")
name = app.config.get("ROOT_SITE_NAME", _("Your new site"))
description = _(
"This is your new site. This is also your root site, " "and this can be used to create other sites."
)
root_site, created = Site.objects.get_or_create(
domain=app.config.get("DOMAIN_ROOT"),
defaults={
"name": name,
"description": "<h1>%s</h1><p>%s</p>" % (name, description),
"owner_email": None,
"verified_email": True,
},
)
port = app.config.get("PORT", None)
url = "//%s" % root_site.domain
if port:
url += ":%d" % port
if created:
return redirect(url)
else:
return redirect("%s%s" % (url, url_for("sites")))
g.user = session.get("username", None)
if "menu" in g.site.active_modules:
g.menu, created = Menu.objects.get_or_create(site=g.site.domain)
else:
g.menu = None
开发者ID:sigurdga,项目名称:samklang,代码行数:35,代码来源:app.py
示例10: user_recovery_page
def user_recovery_page(site, host, netloc, csrf, user_id, user_hash):
"""
User recovery page url
"""
# Logout
session = request.environ.get('beaker.session')
session['logged_in'] = False
session['user_id_logged_in'] = None
# User
try:
user = User.get(User.id == user_id, User.user_hash == user_hash)
except User.DoesNotExist:
return dict(site=site, host=host, csrf=csrf, recovery=False)
# Site
try:
site = Site.get(Site.user == user)
except Site.DoesNotExist:
return dict(site=site, host=host, csrf=csrf, recovery=False)
# Verify actived user and actived site
if (not user.active) or (not site.active):
return dict(site=site, host=host, csrf=csrf, recovery=False)
# Login
session['logged_in'] = True
session['user_id_logged_in'] = user.get_id()
# Return OK
return dict(site=site, host=host, csrf=csrf, recovery=True, user=user)
开发者ID:jfmedeirosneto,项目名称:opcms,代码行数:32,代码来源:opcms_user.py
示例11: observation_update2
def observation_update2(site_key):
site = Site.get_by_key_name(site_key)
if site is None:
return Response(status = 404)
url = "http://www.metoffice.gov.uk/public/data/PWSCache/BestForecast/Observation/%s?format=application/json" % site_key
result = urlfetch.fetch(url)
if result.status_code == 200:
observations = parse_observation(result.content)
# issued_date = parse_date(forecast["@dataDate"])
for date, data in timesteps(observations):
obs_timestep = ObservationTimestep.get_by_site_and_datetime(site, date)
if obs_timestep is None:
obs_timestep = ObservationTimestep(site = site, observation_datetime = date, observation_date = date.date())
for k,v in data.items():
prop_name = snake_case(k)
if hasattr(obs_timestep, prop_name):
if v == "missing":
v = None
elif prop_name == 'temperature':
v = float(v)
setattr(obs_timestep, prop_name, v)
obs_timestep.save()
#logging.info("%s, %s" % (str(date), str(ObservationTimestep)))
return Response(status = 204)
开发者ID:tempredirect,项目名称:MetOfficeWatch,代码行数:30,代码来源:views.py
示例12: forecast_update
def forecast_update(site_key):
site = Site.get_by_key_name(site_key)
if site is None:
return Response(status = 404)
forecast_url = "http://www.metoffice.gov.uk/public/data/PWSCache/BestForecast/Forecast/%s?format=application/json" % site_key
result = urlfetch.fetch(forecast_url)
if result.status_code == 200:
forecast = parse_forecast(result.content)
issued_date = parse_date(forecast["@dataDate"])
for date, day in days(forecast):
forecast_day = ForecastDay.get_by_key_name(make_key_name(site,date))
if forecast_day is None:
forecast_day = ForecastDay(key_name=make_key_name(site,date), forecast_date = date, site = site)
forecast_day.site = site
for timestep, data in day_timesteps(day):
w = Forecast()
w.issued = issued_date
for k,v in data.items():
prop_name = snake_case(k)
if hasattr(w, prop_name):
if v == "missing":
v = None
setattr(w, prop_name, v)
forecast_day.forecasts.add(timestep,w)
forecast_day.save()
site.save()
return Response(status = 204)
开发者ID:tempredirect,项目名称:MetOfficeWatch,代码行数:31,代码来源:views.py
示例13: forecast_update2
def forecast_update2(site_key):
site = Site.get_by_key_name(site_key)
if site is None:
return Response(status = 404)
forecast_url = "http://www.metoffice.gov.uk/public/data/PWSCache/BestForecast/Forecast/%s?format=application/json" % site_key
result = urlfetch.fetch(forecast_url)
if result.status_code == 200:
forecast = parse_forecast(result.content)
issued_date = parse_date(forecast["@dataDate"])
for date, data in timesteps(forecast):
forecast_timestep = ForecastTimestep.find_by_site_and_dates(site, date, issued_date)
if forecast_timestep is None:
forecast_timestep = ForecastTimestep(site = site, forecast_datetime = date, issued_datetime = issued_date, forecast_date = date.date())
for k,v in data.items():
prop_name = snake_case(k)
if hasattr(forecast_timestep, prop_name):
if v == "missing":
v = None
setattr(forecast_timestep, prop_name, v)
forecast_timestep.save()
return Response(status = 204)
开发者ID:tempredirect,项目名称:MetOfficeWatch,代码行数:26,代码来源:views.py
示例14: rewrite_result
def rewrite_result(result):
'''\
Rewrites the HTML in this result (question, answers and comments) so
links to other StackExchange sites that exist in Stackdump are rewritten,
links elsewhere are decorated with a CSS class, and all images are replaced
with a placeholder.
The JSON must have been decoded first.
'''
app_url_root = settings.APP_URL_ROOT
# get a list of all the site base URLs
sites = list(Site.select())
sites_by_urls = dict([ (s.base_url, s) for s in sites ])
# rewrite question
question = result.get('question')
if question:
question['body'] = _rewrite_html(question.get('body'), app_url_root, sites_by_urls)
for c in question.get('comments', [ ]):
c['text'] = _rewrite_html(c.get('text'), app_url_root, sites_by_urls)
# rewrite answers
answers = result.get('answers')
if answers:
for a in answers:
a['body'] = _rewrite_html(a.get('body'), app_url_root, sites_by_urls)
for c in a.get('comments', [ ]):
c['text'] = _rewrite_html(c.get('text'), app_url_root, sites_by_urls)
开发者ID:eplanet,项目名称:offstack,代码行数:29,代码来源:server.py
示例15: view_question
def view_question(site_key, question_id, answer_id=None):
context = { }
try:
context['site'] = Site.selectBy(key=site_key).getOne()
except SQLObjectNotFound:
raise HTTPError(code=404, output='No site exists with the key %s.' % site_key)
# get the question referenced by this question id
query = 'id:%s siteKey:%s' % (question_id, site_key)
results = solr_conn().search(query)
if len(results) == 0:
raise HTTPError(code=404, output='No question exists with the ID %s for the site, %s.' % (question_id, context['site'].name))
decode_json_fields(results)
retrieve_users(results)
retrieve_sites(results)
result = results.docs[0]
convert_comments_to_html(result)
if settings.REWRITE_LINKS_AND_IMAGES:
rewrite_result(result)
sort_answers(result)
context['result'] = result
context['answer_id'] = answer_id
return render_template('question.html', context)
开发者ID:eplanet,项目名称:offstack,代码行数:28,代码来源:server.py
示例16: login_recovery
def login_recovery(site, host, netloc, csrf):
"""
Recovery post url
"""
# Logout
session = request.environ.get('beaker.session')
session['logged_in'] = False
session['user_id_logged_in'] = None
# POST parameters
email = request.POST.getunicode('email')
# User
try:
user = User.get(User.email == email)
except User.DoesNotExist:
return dict(status=False, info='Usuário não encontrado')
# Site
try:
site = Site.get(Site.user == user)
except Site.DoesNotExist:
return dict(status=False, info='Site não encontrado')
# Send recovery email
send_recovery_email(host, DEFAULT_SENDER, user)
# Return OK
return dict(status=True, info='Solicitado senha com sucesso. Acesse seu email para recuperar sua senha.')
开发者ID:jfmedeirosneto,项目名称:opcms,代码行数:30,代码来源:opcms_login.py
示例17: latest_obs_and_forecast
def latest_obs_and_forecast(site_id):
result = memcache.get(site_id, "site_latest")
if result:
return result
site = Site.get_by_key_name(site_id)
if site is None:
return None
obs = ObservationTimestep.find_latest_by_site(site, limit=6)
result = None
if len(obs) > 0:
forecasts = ForecastTimestep.find_by_site_closest_by_date(site, first(obs).observation_datetime,
limit=50)
closest_forecast = first(forecasts)
if closest_forecast:
matching_obs = first(filter(lambda o: o.observation_datetime == closest_forecast.forecast_datetime, obs))
matching_forecasts = ifilter(lambda f: f.forecast_datetime == closest_forecast.forecast_datetime, forecasts)
if matching_obs:
#finally have both... a single obs report and multiple forecasts
obs_dict = to_dict_excl_sites(matching_obs)
obs_dict['best_forecast'] = map(to_dict_excl_sites, make_five_day_list(matching_forecasts))
result = {
'site': site.to_dict(),
'observation': obs_dict
}
memcache.set(site_id, result, 60 * 60, namespace='site_latest')
return result
开发者ID:tempredirect,项目名称:MetOfficeWatch,代码行数:31,代码来源:dataccess.py
示例18: site_update
def site_update(self, request):
"""Update info a site"""
entity = Site.site_update(request)
if entity:
return entity
else:
raise endpoints.NotFoundException()
开发者ID:danluzhen,项目名称:Rapimando,代码行数:7,代码来源:api.py
示例19: seed_node
def seed_node(site_id = None, alias = None, latitude = None, longitude = None):
if site_id:
site = Site.query.filter_by(id = site_id).first()
else:
site = Site.create(name = 'Techrice site {}'.format(uuid4().hex))
if not alias:
alias = 'Techrice node {}'.format(uuid4().hex)
node = Node.create(name = alias, site = site, latitude = latitude, longitude = longitude)
solar = Sensor.create(node = node, sensortype = SensorType.query.filter_by(name = 'solar voltage').first(), name = 'vsol')
battery = Sensor.create(node = node, sensortype = SensorType.query.filter_by(name = 'battery voltage').first(), name = 'vbat')
temperature = Sensor.create(node = node, sensortype = SensorType.query.filter_by(name = 'DHT11 temperature').first(), name = 'temperature')
humidity = Sensor.create(node = node, sensortype = SensorType.query.filter_by(name = 'DHT11 humidity').first(), name = 'humidity')
sonar = Sensor.create(node = node, sensortype = SensorType.query.filter_by(name = 'sonar HC SR-04').first(), name = 'sonar')
header = Header.get_header(node_id = node.id)
print header
return {
'node': 'name: {}, id: {}, longitude: {}, latitude: {}'.format(node.name, node.id, node.longitude, node.latitude),
'sensors': map(lambda s: 'name: {}, id: {}'.format(s.name, s.id), node.sensors),
'header' : header
}
开发者ID:Hackerfarm,项目名称:techrice,代码行数:25,代码来源:seed.py
示例20: get
def get(self):
sites = Site.all()
context = {
'sites': sites,
}
sites_for_output = {}
# loop over the sites
for site in sites:
# and store each one in the output variable
site_for_output = {
"url": site.url,
"issues": site.issue_set.count(),
}
sites_for_output[site.name] = site_for_output
# create the JSON object we're going to return
json = simplejson.dumps(sites_for_output, sort_keys=False)
# serve the response with the correct content type
#self.response.headers['Content-Type'] = 'application/json'
# write the json to the response
self.response.out.write(json)
开发者ID:4sp1r3,项目名称:fixmysite,代码行数:26,代码来源:main.py
注:本文中的models.Site类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论