Here are the examples of the python api django.http.HttpResponse taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
162 Examples
0
Example 51
Project: CommunityCellularManager Source File: staff.py
def get(self, request):
""""Handles GET requests."""
user_profile = models.UserProfile.objects.get(user=request.user)
if not user_profile.user.is_staff:
return response.Response('', status=status.HTTP_404_NOT_FOUND)
# Build up the context and initial form data.
initial_form_data = {}
context = {
'networks': get_objects_for_user(request.user, 'view_network', klass=models.Network),
'user_profile': user_profile,
}
network_pk = request.GET.get('network', None)
if network_pk:
initial_form_data['network'] = network_pk
network = models.Network.objects.get(pk=network_pk)
# Attach the associated UserProfile to the network for reference.
network.user_profile = models.UserProfile.objects.get(
network=network)
context['network'] = network
# Count subs and numbers.
context['subscriber_count'] = models.Subscriber.objects.filter(
network=network).count()
context['number_count'] = models.Number.objects.filter(
network=network).count()
# Build up the data for the price comparison table.
context['prices'] = []
context['grand_total_op_profit'] = 0
context['grand_total_e_profit'] = 0
tiers = self.get_ordered_tiers(network)
for traffic_type in ('call', 'sms'):
for tier in tiers:
# Determine costs. The URL params (keys) are of the form
# <call/sms>_<sluggified_tier_name>_proposed_<entity>_cost.
# We'll fill in the form with something that was POSTed or
# with a default value from the tier itself.
if traffic_type == 'call':
# Subscriber costs.
actual_sub_cost = tier.cost_to_subscriber_per_min
key = 'call_%s_proposed_%s_cost' % (
slugify(tier.name), 'sub')
proposed_sub_cost = int(request.GET.get(
key, actual_sub_cost))
# Operator costs.
actual_op_cost = tier.cost_to_operator_per_min
key = 'call_%s_proposed_%s_cost' % (
slugify(tier.name), 'op')
proposed_op_cost = int(request.GET.get(
key, actual_op_cost))
# Endaga costs.
actual_e_cost = self.get_cost(tier, 'call', 'e')
key = 'call_%s_proposed_%s_cost' % (
slugify(tier.name), 'e')
proposed_e_cost = int(request.GET.get(
key, actual_e_cost))
elif traffic_type == 'sms':
# Subscriber costs.
actual_sub_cost = tier.cost_to_subscriber_per_sms
key = 'sms_%s_proposed_%s_cost' % (
slugify(tier.name), 'sub')
proposed_sub_cost = int(request.GET.get(
key, actual_sub_cost))
# Operator costs.
actual_op_cost = tier.cost_to_operator_per_sms
key = 'sms_%s_proposed_%s_cost' % (
slugify(tier.name), 'op')
proposed_op_cost = int(request.GET.get(
key, actual_op_cost))
# Endaga costs.
actual_e_cost = self.get_cost(tier, 'sms', 'e')
key = 'sms_%s_proposed_%s_cost' % (
slugify(tier.name), 'e')
proposed_e_cost = int(request.GET.get(
key, actual_e_cost))
# Calculate margins.
op_margin = proposed_sub_cost - proposed_op_cost
e_margin = proposed_op_cost - proposed_e_cost
# Find the number of these kinds of events.
occurrences = self.count_usage_events(traffic_type, tier)
# Calculate profits in dollars.
total_op_profit = occurrences * op_margin / (1000 * 100.)
total_e_profit = occurrences * e_margin / (1000 * 100.)
context['grand_total_op_profit'] += total_op_profit
context['grand_total_e_profit'] += total_e_profit
# Now that we've done the math, format the values.
if traffic_type == 'call':
occurrences = '%0.2f' % occurrences
# Use all of this to set more of the context.
context['prices'].append({
'directionality': tier.directionality,
'tier': tier.name,
'traffic_type': traffic_type,
'proposed_sub_cost': proposed_sub_cost,
'actual_sub_cost': actual_sub_cost,
'proposed_op_cost': proposed_op_cost,
'actual_op_cost': actual_op_cost,
'proposed_e_cost': proposed_e_cost,
'actual_e_cost': actual_e_cost,
'op_margin': op_margin,
'e_margin': e_margin,
'occurrences': occurrences,
'total_op_profit': total_op_profit,
'total_e_profit': total_e_profit,
})
# Attach the network selection form with any specified initial data.
select_network_form = SelectNetworkForm(initial=initial_form_data)
select_network_form.helper.form_action = (
'/dashboard/staff/margin-analysis')
context['select_network_form'] = select_network_form
# Render the template.
margin_template = template.loader.get_template(
'dashboard/staff/margin-analysis.html')
html = margin_template.render(context, request)
return http.HttpResponse(html)
0
Example 52
Project: django-powerdns-manager Source File: views.py
@csrf_exempt
def dynamic_ip_update_view(request):
"""
TODO: explain dynamic IP update options and logic
if hostname is missing, the ips of all A and AAAA records of the zone are changed
otherwise only the specific record with the name=hostname and provided that the
correct ip (v4, v6) has been provided for the type of the record (A, AAAA)
If no ipv4 or ipv6 address is provided, then the client IP address is used
to update A records (if the client IP is IPv4) or AAAA records (if client IP is IPv6).
curl -k \
-F "api_key=UBSE1RJ0J175MRAMJC31JFUH" \
-F "hostname=ns1.centos.example.org" \
-F "ipv4=10.1.2.3" \
-F "ipv6=3ffe:1900:4545:3:200:f8ff:fe21:67cf" \
https://centos.example.org/powerdns/update/
"""
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
form = DynamicIPUpdateForm(request.POST)
if not form.is_valid():
return HttpResponseBadRequest(repr(form.errors))
# Determine protocol or REMOTE_ADDR
remote_ipv4 = None
remote_ipv6 = None
try:
validate_ipv4_address(request.META['REMOTE_ADDR'])
except ValidationError:
try:
validate_ipv6_address(request.META['REMOTE_ADDR'])
except ValidationError:
return HttpResponseBadRequest('Cannot determine protocol of remote IP address')
else:
remote_ipv6 = request.META['REMOTE_ADDR']
else:
remote_ipv4 = request.META['REMOTE_ADDR']
# Gather required information
# API key
api_key = form.cleaned_data['api_key']
# Hostname
hostname = form.cleaned_data['hostname']
# If the hostname is missing, the IP addresses of all A and AAAA records
# of the zone are updated.
update_all_hosts_in_zone = False
if not hostname:
update_all_hosts_in_zone = True
# IP addresses
ipv4 = form.cleaned_data['ipv4']
ipv6 = form.cleaned_data['ipv6']
# If IP information is missing, the remote client's IP address will be used.
if not ipv4 and not ipv6:
if remote_ipv4:
ipv4 = remote_ipv4
if remote_ipv6:
ipv6 = remote_ipv6
# All required data is good. Process the request.
DynamicZone = get_model('powerdns_manager', 'DynamicZone')
Record = get_model('powerdns_manager', 'Record')
# Get the relevant dynamic zone instance
dyn_zone = DynamicZone.objects.get(api_key__exact=api_key)
# Get A and AAAA records
dyn_rrs = Record.objects.filter(domain=dyn_zone.domain, type__in=('A', 'AAAA'))
if not dyn_rrs:
return HttpResponseNotFound('A or AAAA resource records not found')
# Check existence of hostname
if hostname:
hostname_exists = False
for rr in dyn_rrs:
if rr.name == hostname:
hostname_exists = True
break
if not hostname_exists:
return HttpResponseNotFound('error:Hostname not found: %s' % hostname)
# Update the IPs
rr_has_changed = False
if update_all_hosts_in_zone: # No hostname supplied
for rr in dyn_rrs:
# Try to update A records
if rr.type == 'A' and ipv4:
rr.content = ipv4
rr_has_changed = True
# Try to update AAAA records
elif rr.type == 'AAAA' and ipv6:
rr.content = ipv6
rr_has_changed = True
rr.save()
else: # A hostname is supplied
for rr in dyn_rrs:
if rr.name == hostname:
# Try to update A records
if rr.type == 'A' and ipv4:
rr.content = ipv4
rr_has_changed = True
# Try to update AAAA records
elif rr.type == 'AAAA' and ipv6:
rr.content = ipv6
rr_has_changed = True
rr.save()
if rr_has_changed:
return HttpResponse('Success')
else:
return HttpResponseNotFound('error:No suitable resource record found')
0
Example 53
Project: django-ses Source File: views.py
@require_POST
def handle_bounce(request):
"""
Handle a bounced email via an SNS webhook.
Parse the bounced message and send the appropriate signal.
For bounce messages the bounce_received signal is called.
For complaint messages the complaint_received signal is called.
See: http://docs.aws.amazon.com/sns/latest/gsg/json-formats.html#http-subscription-confirmation-json
See: http://docs.amazonwebservices.com/ses/latest/DeveloperGuide/NotificationsViaSNS.html
In addition to email bounce requests this endpoint also supports the SNS
subscription confirmation request. This request is sent to the SNS
subscription endpoint when the subscription is registered.
See: http://docs.aws.amazon.com/sns/latest/gsg/Subscribe.html
For the format of the SNS subscription confirmation request see this URL:
http://docs.aws.amazon.com/sns/latest/gsg/json-formats.html#http-subscription-confirmation-json
SNS message signatures are verified by default. This funcionality can
be disabled by setting AWS_SES_VERIFY_BOUNCE_SIGNATURES to False.
However, this is not recommended.
See: http://docs.amazonwebservices.com/sns/latest/gsg/SendMessageToHttp.verify.signature.html
"""
# For Django >= 1.4 use request.body, otherwise
# use the old request.raw_post_data
if hasattr(request, 'body'):
raw_json = request.body
else:
raw_json = request.raw_post_data
try:
notification = json.loads(raw_json.decode('utf-8'))
except ValueError as e:
# TODO: What kind of response should be returned here?
logger.warning('Recieved bounce with bad JSON: "%s"', e)
return HttpResponseBadRequest()
# Verify the authenticity of the bounce message.
if (settings.VERIFY_BOUNCE_SIGNATURES and
not utils.verify_bounce_message(notification)):
# Don't send any info back when the notification is not
# verified. Simply, don't process it.
logger.info('Recieved unverified notification: Type: %s',
notification.get('Type'),
extra={
'notification': notification,
},
)
return HttpResponse()
if notification.get('Type') in ('SubscriptionConfirmation',
'UnsubscribeConfirmation'):
# Process the (un)subscription confirmation.
logger.info('Recieved subscription confirmation: TopicArn: %s',
notification.get('TopicArn'),
extra={
'notification': notification,
},
)
# Get the subscribe url and hit the url to confirm the subscription.
subscribe_url = notification.get('SubscribeURL')
try:
urlopen(subscribe_url).read()
except URLError as e:
# Some kind of error occurred when confirming the request.
logger.error('Could not confirm subscription: "%s"', e,
extra={
'notification': notification,
},
exc_info=True,
)
elif notification.get('Type') == 'Notification':
try:
message = json.loads(notification['Message'])
except ValueError as e:
# The message isn't JSON.
# Just ignore the notification.
logger.warning('Recieved bounce with bad JSON: "%s"', e, extra={
'notification': notification,
})
else:
mail_obj = message.get('mail')
notification_type = message.get('notificationType')
if notification_type == 'Bounce':
# Bounce
bounce_obj = message.get('bounce', {})
# Logging
feedback_id = bounce_obj.get('feedbackId')
bounce_type = bounce_obj.get('bounceType')
bounce_subtype = bounce_obj.get('bounceSubType')
logger.info(
'Recieved bounce notification: feedbackId: %s, bounceType: %s, bounceSubType: %s',
feedback_id, bounce_type, bounce_subtype,
extra={
'notification': notification,
},
)
signals.bounce_received.send(
sender=handle_bounce,
mail_obj=mail_obj,
bounce_obj=bounce_obj,
raw_message=raw_json,
)
elif notification_type == 'Complaint':
# Complaint
complaint_obj = message.get('complaint', {})
# Logging
feedback_id = complaint_obj.get('feedbackId')
feedback_type = complaint_obj.get('complaintFeedbackType')
logger.info('Recieved complaint notification: feedbackId: %s, feedbackType: %s',
feedback_id, feedback_type,
extra={
'notification': notification,
},
)
signals.complaint_received.send(
sender=handle_bounce,
mail_obj=mail_obj,
complaint_obj=complaint_obj,
raw_message=raw_json,
)
else:
# We received an unknown notification type. Just log and
# ignore it.
logger.warning("Recieved unknown notification", extra={
'notification': notification,
})
else:
logger.info('Recieved unknown notification type: %s',
notification.get('Type'),
extra={
'notification': notification,
},
)
# AWS will consider anything other than 200 to be an error response and
# resend the SNS request. We don't need that so we return 200 here.
return HttpResponse()
0
Example 54
Project: open-context-py Source File: views.py
def html_view(request, spatial_context=None):
mem_cache_obj = MemoryCache()
mem_cache_obj.ping_redis_server()
rp = RootPath()
base_url = rp.get_baseurl()
rd = RequestDict()
request_dict_json = rd.make_request_dict_json(request,
spatial_context)
if rd.security_ok is False:
# looks like an abusive SQL injection request
template = loader.get_template('400.html')
context = RequestContext(request,
{'abusive': True})
return HttpResponse(template.render(context), status=400)
elif rd.do_bot_limit:
# redirect bot requests away from faceted search where
# they can negatively impact performance
cache_control(no_cache=True)
return redirect('/search/', permanent=False)
else:
# url and json_url neeed for view templating
url = request.get_full_path()
if 'http://' not in url \
and 'https://' not in url:
url = base_url + url
if '?' in url:
json_url = url.replace('?', '.json?')
else:
json_url = url + '.json'
# see if search results are cached. this is not done
# with a view decorator, because we want to handle bots differently
db_cache = DatabaseCache()
cache_key = db_cache.make_cache_key('search',
request_dict_json)
mem_key = mem_cache_obj.make_memory_cache_key('search-json',
request_dict_json)
# print('Cache key: ' + cache_key)
geo_proj = False
json_ld = None
if rd.refresh_cache:
# the request wanted to refresh the cache
db_cache.remove_cache_object(cache_key)
mem_cache_obj.remove_cache_object(mem_key)
if 'response' in request.GET:
if 'geo-project' in request.GET['response']:
geo_proj = True
json_ld = mem_cache_obj.get_cache_object(mem_key)
# get the search result JSON-LD, if it exists in cache
json_ld = db_cache.get_cache_object(cache_key)
if json_ld is None:
# cached result is not found, so make it with a new search
solr_s = SolrSearch()
solr_s.is_bot = rd.is_bot # True if bot detected
solr_s.do_bot_limit = rd.do_bot_limit # Toggle limits on facets for bots
solr_s.mem_cache_obj = mem_cache_obj
if solr_s.solr is not False:
response = solr_s.search_solr(request_dict_json)
mem_cache_obj = solr_s.mem_cache_obj # reused cached memory items
m_json_ld = MakeJsonLd(request_dict_json)
m_json_ld.base_search_link = '/search/'
# share entities already looked up. Saves database queries
m_json_ld.mem_cache_obj = mem_cache_obj
m_json_ld.request_full_path = request.get_full_path()
m_json_ld.spatial_context = spatial_context
json_ld = m_json_ld.convert_solr_json(response.raw_content)
# now cache the resulting JSON-LD
db_cache.save_cache_object(cache_key, json_ld)
if geo_proj:
mem_cache_obj.save_cache_object(mem_key)
if json_ld is not None:
req_neg = RequestNegotiation('text/html')
req_neg.supported_types = ['application/json',
'application/ld+json',
'application/vnd.geo+json']
if 'HTTP_ACCEPT' in request.META:
req_neg.check_request_support(request.META['HTTP_ACCEPT'])
if 'json' in req_neg.use_response_type:
# content negotiation requested JSON or JSON-LD
recon_obj = Reconciliation()
json_ld = recon_obj.process(request.GET,
json_ld)
request.content_type = req_neg.use_response_type
return HttpResponse(json.dumps(json_ld,
ensure_ascii=False, indent=4),
content_type=req_neg.use_response_type + "; charset=utf8")
else:
# now make the JSON-LD into an object suitable for HTML templating
st = SearchTemplate(json_ld)
st.process_json_ld()
template = loader.get_template('search/view.html')
context = RequestContext(request,
{'st': st,
'item_type': '*',
'base_search_link': m_json_ld.base_search_link,
'url': url,
'json_url': json_url,
'base_url': base_url})
if req_neg.supported:
return HttpResponse(template.render(context))
else:
# client wanted a mimetype we don't support
return HttpResponse(req_neg.error_message,
content_type=req_neg.use_response_type + "; charset=utf8",
status=415)
else:
cache_control(no_cache=True)
template = loader.get_template('500.html')
context = RequestContext(request,
{'error': 'Solr Connection Problem'})
return HttpResponse(template.render(context), status=503)
0
Example 55
Project: AuShadha Source File: views.py
@login_required
def patient(request):
if request.method == "GET" and request.is_ajax():
tree = DijitTree()
history = DijitTreeNode({"name": "History",
"type": "application",
"id": "HISTORY"
})
medical_history = DijitTreeNode({"name": "Medical History",
"type": "medical_history_module",
"id": "MEDICAL_HISTORY"
})
history.add_child_node(medical_history)
surgical_history = DijitTreeNode({"name": "Surgical History",
"type": "surgical_history_module",
"id": "SURGICAL_HISTORY"
})
history.add_child_node(surgical_history)
family_history = DijitTreeNode({"name": "Family History",
"type": "family_history_module",
"id": "FAMILY_HISTORY"
})
history.add_child_node(family_history)
social_history = DijitTreeNode({"name": "Social History",
"type": "social_history_module",
"id": "SOCIAL_HISTORY"
})
history.add_child_node(social_history)
demographics = DijitTreeNode({"name": "Demographics",
"type": "demographics_module",
"id": "DEMOGRAPHICS"
})
history.add_child_node(demographics)
tree.add_child_node(history)
medication_list = DijitTreeNode({"name" : "Medications",
"type": "application",
"module_type": "medication_list_module",
"id" : "MEDICATIONS"
})
tree.add_child_node(medication_list)
preventives = DijitTreeNode({"name": "Preventives",
"type": "application",
"id": "PREVENTIVES"
})
immunisation = DijitTreeNode({"name": "Immunisation",
"type": "immunisation_module",
"id": "IMMUNISATION"
})
preventives.add_child_node(immunisation)
tree.add_child_node(preventives)
#medical_preventives = DijitTreeNode({"name": "Medical",
#"type": "medical_preventives_module",
#"id": "MEDICAL_PREVENTIVES"
#})
#surgical_preventives = DijitTreeNode({"name": "Surgical",
#"type": "surgical_preventives_module",
#"id": "SURGICAL_PREVENTIVES"
#})
#obs_and_gyn_preventives = DijitTreeNode({"name": "Obs & Gyn",
#"type": "obs_and_gyn_preventives_module",
#"id": "OBS_PREVENTIVES"
#})
#admission = DijitTreeNode({"name" : "AdmissionDetails" ,
#"type" :"application",
#"id" :"ADM"
#})
#visit = DijitTreeNode({"name" : "OPD Visits" ,
#"type":"application",
#"id":"VISIT"
#})
investigation = DijitTreeNode({"name": "Investigation",
"type": "application",
"id": "INV"
})
tree.add_child_node(investigation)
imaging = DijitTreeNode({"name": "Imaging",
"type": "application",
"id": "IMAG"
})
tree.add_child_node(imaging)
procedure = DijitTreeNode({"name": "Procedures",
"type": "application",
"id": "PROCEDURES"
})
tree.add_child_node(procedure)
#calendar = DijitTreeNode({"name" : "Calendar" ,
#"type":"application",
#"id":"CAL"
#})
#media = DijitTreeNode({"name": "Media",
#"type": "application",
#"id": "MEDIA"
#})
#docuements = DijitTreeNode({"name": "Docuements",
#"type": "patient_docuements_module",
#"id": "DOCS"
#})
#images = DijitTreeNode({"name": "Images",
#"type": "patient_images_module",
#"id": "IMAGES"
#})
#coding = DijitTreeNode({"name": "Coding",
#"type": "application",
#"id": "CODING"
#})
#icd_10 = DijitTreeNode({"name": "ICD 10",
#"type": "icd10_module",
#"id": "ICD_10"
#})
#icd_10_pcs = DijitTreeNode({"name": "ICD 10 PC",
#"type": "icd10_pcs_module",
#"id": "ICD_10_PROCEDURE_CODES"
#})
jsondata = tree.to_json()
return HttpResponse(jsondata, content_type="application/json")
else:
raise Http404("Bad Request")
0
Example 56
Project: django-cms Source File: placeholderadmin.py
@method_decorator(require_POST)
@xframe_options_sameorigin
def move_plugin(self, request):
"""
Performs a move or a "paste" operation (when «move_a_copy» is set)
POST request with following parameters:
- plugin_id
- placeholder_id
- plugin_language (optional)
- plugin_parent (optional)
- plugin_order (array, optional)
- move_a_copy (Boolean, optional) (anything supplied here except a case-
insensitive "false" is True)
NOTE: If move_a_copy is set, the plugin_order should contain an item
'__COPY__' with the desired destination of the copied plugin.
"""
# plugin_id and placeholder_id are required, so, if nothing is supplied,
# an ValueError exception will be raised by get_int().
try:
plugin_id = get_int(request.POST.get('plugin_id'))
except TypeError:
raise RuntimeError("'plugin_id' is a required parameter.")
plugin = (
CMSPlugin
.objects
.select_related('placeholder')
.get(pk=plugin_id)
)
try:
placeholder_id = get_int(request.POST.get('placeholder_id'))
except TypeError:
raise RuntimeError("'placeholder_id' is a required parameter.")
except ValueError:
raise RuntimeError("'placeholder_id' must be an integer string.")
placeholder = Placeholder.objects.get(pk=placeholder_id)
# The rest are optional
parent_id = get_int(request.POST.get('plugin_parent', ""), None)
language = request.POST.get('plugin_language', None)
move_a_copy = request.POST.get('move_a_copy', False)
move_a_copy = (move_a_copy and move_a_copy != "0" and
move_a_copy.lower() != "false")
source_language = plugin.language
source_placeholder = plugin.placeholder
if not language and plugin.language:
language = plugin.language
order = request.POST.getlist("plugin_order[]")
if placeholder != source_placeholder:
try:
template = self.get_placeholder_template(request, placeholder)
has_reached_plugin_limit(placeholder, plugin.plugin_type,
plugin.language, template=template)
except PluginLimitReached as er:
return HttpResponseBadRequest(er)
if move_a_copy: # "paste"
if plugin.plugin_type == "PlaceholderPlugin":
parent_id = None
inst = plugin.get_plugin_instance()[0]
plugins = inst.placeholder_ref.get_plugins()
else:
plugins = [plugin] + list(plugin.get_descendants())
if not self.has_copy_from_clipboard_permission(request, placeholder, plugins):
return HttpResponseForbidden(
force_text(_("You have no permission to paste this plugin")))
new_plugins = copy_plugins.copy_plugins_to(
plugins,
placeholder,
language,
parent_plugin_id=parent_id,
)
top_plugins = []
top_parent = new_plugins[0][0].parent_id
for new_plugin, old_plugin in new_plugins:
if new_plugin.parent_id == top_parent:
# NOTE: There is no need to save() the plugins here.
new_plugin.position = old_plugin.position
top_plugins.append(new_plugin)
# Creates a list of string PKs of the top-level plugins ordered by
# their position.
top_plugins_pks = [str(p.pk) for p in sorted(
top_plugins, key=lambda x: x.position)]
if parent_id:
parent = CMSPlugin.objects.get(pk=parent_id)
for plugin in top_plugins:
plugin.parent = parent
plugin.placeholder = placeholder
plugin.language = language
plugin.save()
# If an ordering was supplied, we should replace the item that has
# been copied with the new copy
if order:
if '__COPY__' in order:
copy_idx = order.index('__COPY__')
del order[copy_idx]
order[copy_idx:0] = top_plugins_pks
else:
order.extend(top_plugins_pks)
# Set the plugin variable to point to the newly created plugin.
plugin = new_plugins[0][0]
else:
# Regular move
if not self.has_move_plugin_permission(request, plugin, placeholder):
return HttpResponseForbidden(
force_text(_("You have no permission to move this plugin")))
plugin_data = {
'language': language,
'placeholder': placeholder,
}
if parent_id:
if plugin.parent_id != parent_id:
parent = CMSPlugin.objects.get(pk=parent_id)
if parent.placeholder_id != placeholder.pk:
return HttpResponseBadRequest(force_text(
_('parent must be in the same placeholder')))
if parent.language != language:
return HttpResponseBadRequest(force_text(
_('parent must be in the same language as '
'plugin_language')))
plugin = plugin.update(refresh=True, parent=parent, **plugin_data)
plugin = plugin.move(parent, pos='last-child')
else:
plugin = plugin.update(refresh=True, **plugin_data)
else:
target = CMSPlugin.get_last_root_node()
plugin = plugin.update(refresh=True, parent=None, **plugin_data)
plugin = plugin.move(target, pos='right')
# Update all children to match the parent's
# language and placeholder
plugin.get_descendants().update(**plugin_data)
if order:
# order should be a list of plugin primary keys
# it's important that the plugins being referenced
# are all part of the same tree.
order = [int(pk) for pk in order]
plugins_in_tree = CMSPlugin.objects.filter(
parent=parent_id,
placeholder=placeholder,
language=language,
pk__in=order,
)
if len(order) != plugins_in_tree.count():
# Seems like order does not match the tree on the db
message = _('order parameter references plugins in different trees')
return HttpResponseBadRequest(force_text(message))
# Mark the target placeholder as dirty
placeholder.mark_as_dirty(language)
if placeholder != source_placeholder:
# Plugin is being moved or copied into a separate placeholder
# Mark source placeholder as dirty
source_placeholder.mark_as_dirty(source_language)
reorder_plugins(placeholder, parent_id, language, order)
# When this is executed we are in the admin class of the source placeholder
# It can be a page or a model with a placeholder field.
# Because of this we need to get the admin class instance of the
# target placeholder and call post_move_plugin() on it.
# By doing this we make sure that both the source and target are
# informed of the operation.
target_placeholder_admin = self._get_attached_admin(placeholder)
if move_a_copy: # "paste"
plugins = list(plugin.get_tree())
self.post_copy_plugins(request, source_placeholder, placeholder, plugins)
if (target_placeholder_admin and
target_placeholder_admin.model != self.model):
target_placeholder_admin.post_copy_plugins(
request,
source_placeholder=source_placeholder,
target_placeholder=placeholder,
plugins=plugins,
)
else:
self.post_move_plugin(request, source_placeholder, placeholder, plugin)
if (target_placeholder_admin and
target_placeholder_admin.model != self.model):
target_placeholder_admin.post_move_plugin(
request,
source_placeholder=source_placeholder,
target_placeholder=placeholder,
plugin=plugin,
)
try:
language = request.toolbar.toolbar_language
except AttributeError:
language = get_language_from_request(request)
with force_language(language):
plugin_urls = plugin.get_action_urls()
json_response = {
'urls': plugin_urls,
'reload': move_a_copy or requires_reload(
PLUGIN_MOVE_ACTION, [plugin])
}
return HttpResponse(
json.dumps(json_response), content_type='application/json')
0
Example 57
Project: geonode Source File: views.py
@login_required
def docuement_metadata(
request,
docid,
template='docuements/docuement_metadata.html'):
docuement = None
try:
docuement = _resolve_docuement(
request,
docid,
'base.change_resourcebase_metadata',
_PERMISSION_MSG_METADATA)
except Http404:
return HttpResponse(
loader.render_to_string(
'404.html', RequestContext(
request, {
})), status=404)
except PermissionDenied:
return HttpResponse(
loader.render_to_string(
'401.html', RequestContext(
request, {
'error_message': _("You are not allowed to edit this docuement.")})), status=403)
if docuement is None:
return HttpResponse(
'An unknown error has occured.',
content_type="text/plain",
status=401
)
else:
poc = docuement.poc
metadata_author = docuement.metadata_author
topic_category = docuement.category
if request.method == "POST":
docuement_form = DocuementForm(
request.POST,
instance=docuement,
prefix="resource")
category_form = CategoryForm(
request.POST,
prefix="category_choice_field",
initial=int(
request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None)
else:
docuement_form = DocuementForm(instance=docuement, prefix="resource")
category_form = CategoryForm(
prefix="category_choice_field",
initial=topic_category.id if topic_category else None)
if request.method == "POST" and docuement_form.is_valid(
) and category_form.is_valid():
new_poc = docuement_form.cleaned_data['poc']
new_author = docuement_form.cleaned_data['metadata_author']
new_keywords = docuement_form.cleaned_data['keywords']
new_category = TopicCategory.objects.get(
id=category_form.cleaned_data['category_choice_field'])
if new_poc is None:
if poc is None:
poc_form = ProfileForm(
request.POST,
prefix="poc",
instance=poc)
else:
poc_form = ProfileForm(request.POST, prefix="poc")
if poc_form.is_valid():
if len(poc_form.cleaned_data['profile']) == 0:
# FIXME use form.add_error in django > 1.7
errors = poc_form._errors.setdefault('profile', ErrorList())
errors.append(_('You must set a point of contact for this resource'))
poc = None
if poc_form.has_changed and poc_form.is_valid():
new_poc = poc_form.save()
if new_author is None:
if metadata_author is None:
author_form = ProfileForm(request.POST, prefix="author",
instance=metadata_author)
else:
author_form = ProfileForm(request.POST, prefix="author")
if author_form.is_valid():
if len(author_form.cleaned_data['profile']) == 0:
# FIXME use form.add_error in django > 1.7
errors = author_form._errors.setdefault('profile', ErrorList())
errors.append(_('You must set an author for this resource'))
metadata_author = None
if author_form.has_changed and author_form.is_valid():
new_author = author_form.save()
if new_poc is not None and new_author is not None:
the_docuement = docuement_form.save()
the_docuement.poc = new_poc
the_docuement.metadata_author = new_author
the_docuement.keywords.add(*new_keywords)
Docuement.objects.filter(id=the_docuement.id).update(category=new_category)
if getattr(settings, 'SLACK_ENABLED', False):
try:
from geonode.contrib.slack.utils import build_slack_message_docuement, send_slack_messages
send_slack_messages(build_slack_message_docuement("docuement_edit", the_docuement))
except:
print "Could not send slack message for modified docuement."
return HttpResponseRedirect(
reverse(
'docuement_detail',
args=(
docuement.id,
)))
if poc is not None:
docuement_form.fields['poc'].initial = poc.id
poc_form = ProfileForm(prefix="poc")
poc_form.hidden = True
if metadata_author is not None:
docuement_form.fields['metadata_author'].initial = metadata_author.id
author_form = ProfileForm(prefix="author")
author_form.hidden = True
return render_to_response(template, RequestContext(request, {
"docuement": docuement,
"docuement_form": docuement_form,
"poc_form": poc_form,
"author_form": author_form,
"category_form": category_form,
}))
0
Example 58
Project: django-riv Source File: resources.py
def _response_postprocessing(self, request, response=None, exception=None):
"""
Processes the response of the handling method to ensure that we always
return a REST compliant response.
We expect one of the following results from the handling method:
- a 2xx response
- a 2xx response with an invalid form
- an arbitrary unhandled exception
- an Http404 exception
- a 3xx response (redirect)
- a 4xx or 5xx error code
- a response object which is not an HttpResponse instance
Did we miss something?
"""
if not response and not exception:
return HttpResponseServerError()
if isinstance(response, RestResponse):
response = self._rest_to_http_response(request, response)
if (exception and isinstance(exception, Http404)) or \
(response and response.status_code == 404):
if settings.DEBUG and self.display_errors and exception:
return HttpResponseNotFound(exception)
else:
return HttpResponseNotFound()
if exception:
if settings.DEBUG and self.display_errors:
raise
else:
return HttpResponseServerError()
if response and response.status_code == 500:
return HttpResponseServerError()
if response and not isinstance(response, HttpResponse):
if settings.DEBUG and self.display_errors:
return response
else:
return HttpResponseServerError()
if response.status_code >= 300 and response.status_code < 400:
if self._meta.redirect_as_error:
if not self._meta.redirect_as_error_code:
if settings.DEBUG and self.display_errors:
raise ConfigurationError('redirect_as_error defined without redirect_as_error_code')
else:
raise HttpResponseServerError()
return HttpResponse(status=self._meta.redirect_as_error_code)
if request.rest_info.request_method == 'DELETE':
if response.status_code == 200 and not self._meta.render_object_after_creation:
return HttpResponseNoContent()
elif request.rest_info.request_method in ['POST', 'PUT']:
if response.status_code == 200:
if response.content == '':
# We can not simply return "HttpResponseNoContent" here, because
# the current response object has a "Location" header set!
response.status_code = 204
else:
if request.rest_info.request_method == 'POST' or (request.rest_info.request_method == 'PUT' and request.rest_info.request_type == 'list'):
response.status_code = 201
# Responses with 1xx do not make sense. And the HttpRequest class of Django
# has no ability to check for the protocol version. Which is required, as
# Http/1.0 does not now about 1xx codes.
if response.status_code >= 100 and response.status_code < 200:
return HttpResponseServerError()
# The following codes require additional checking.
if response.status_code == 206 and not (\
# the "None" in HttpResponse.get() is necessary for Django versions < 1.4
(response.get('Content-Range', None) or response.get('Content-type', None) == 'multipart/byteranges') and \
(response.get('Date', None)) and \
(response.get('ETag', None) or response.get('Content-Location', None)) and \
(response.get('Expires', None) and response.get('Cache-Control') or response.get('Vary', None))):
return HttpResponseServerError()
elif response.status_code == 401 and not response.get('WWW-Authenticate', None):
# TODO: Check header
return HttpResponseServerError()
elif response.status_code == 405 and not response.get('Allow', None):
return HttpResponseServerError()
elif response.status_code == 200:
return response
return response
0
Example 59
Project: ganetimgr Source File: __init__.py
@csrf_exempt
@login_required
def tagInstance(request, instance):
'''
Set a new instance tag, or delete a tag.
'''
try:
# get instance
instance = Instance.objects.get(name=instance)
except ObjectDoesNotExist:
raise Http404()
# get cluster
cluster = instance.cluster
# get cache key
cache_key = "cluster:%s:instance:%s:user:%s" % (
cluster.slug, instance.name,
request.user.username
)
# check if the object has been cached
res = cache.get(cache_key)
if res is None:
# if not, we must see if the user requested
# the change, has permissions to do so.
res = False
if (
request.user.is_superuser or
request.user in instance.users or
set.intersection(
set(request.user.groups.all()),
set(instance.groups)
)
):
res = True
cache.set(cache_key, res, 90)
if not res:
t = get_template("403.html")
return HttpResponseForbidden(content=t.render(RequestContext(request)))
if request.method == 'POST':
users = []
for user in instance.users:
users.append("u_%s" % user.pk)
groups = []
for group in instance.groups:
groups.append("g_%s" % group.pk)
existingugtags = users + groups
form = tagsForm(request.POST)
if form.is_valid():
newtags = form.cleaned_data['tags']
newtags = newtags.split(',')
common = list(set(existingugtags).intersection(set(newtags)))
deltags = list(set(existingugtags) - set(common))
if len(deltags) > 0:
# we have tags to delete
oldtodelete = prepare_tags(deltags)
jobid = instance.cluster.untag_instance(instance.name, oldtodelete)
if not jobid:
return HttpResponse(
json.dumps(
{
'result': 'failure',
'reason': jobid
}
),
mimetype='application/json'
)
newtagstoapply = prepare_tags(newtags)
if len(newtagstoapply) > 0:
instance.cluster.tag_instance(instance.name, newtagstoapply)
res = {'result': 'success'}
return HttpResponse(json.dumps(res), mimetype='application/json')
else:
return render(
request,
'tagging/itags.html',
{
'form': form,
'users': users,
'instance': instance
}
)
elif request.method == 'GET':
form = tagsForm()
users = []
for user in instance.users:
userd = {}
userd['text'] = user.username
userd['id'] = "u_%s" % user.pk
userd['type'] = "user"
users.append(userd)
for group in instance.groups:
groupd = {}
groupd['text'] = group.name
groupd['id'] = "g_%s" % group.pk
groupd['type'] = "group"
users.append(groupd)
return render(
request,
'tagging/itags.html',
{
'form': form,
'users': users,
'instance': instance
}
)
0
Example 60
Project: datal Source File: views.py
@require_POST
def update_list(request):
account = request.account
auth_manager = request.auth_manager
preferences = account.get_preferences()
language = request.auth_manager.language
resources = ["ds", "vz"]
resources.extend([finder.doc_type for finder in DatalPluginPoint.get_active_with_att('finder')])
if account.get_preference("account.dataset.show"):
resources.append("dt")
form = QueryDatasetForm(request.POST)
if form.is_valid():
query = form.cleaned_data.get('search')
page = form.cleaned_data.get('page')
order = form.cleaned_data.get('order')
order_elastic = None
if order == "0":
order_elastic = "title"
elif order == "1":
order_elastic = "last"
order_type = form.cleaned_data.get('order_type')
reverse = order_type.lower() == 'ascending'
category_filters = form.cleaned_data.get('category_filters')
if category_filters:
category_filters=category_filters.split(",")
builder = ThemeBuilder(preferences, False, language, request.user)
data = builder.parse()
if data['federated_accounts_ids']:
entity = form.cleaned_data.get('entity_filters')
if entity:
accounts_ids = [int(entity)]
else:
accounts_ids = data['federated_accounts_ids'] + [account.id]
typef = form.cleaned_data.get('type_filters')
if typef:
if typef in resources:
resources = [typef]
queryset = FinderQuerySet(FinderManager(HomeFinder),
query = query,
max_results = 250,
account_id = accounts_ids,
resource = resources,
category_filters=category_filters,
order = order_elastic,
reverse = reverse
)
else:
all_resources = form.cleaned_data.get('all')
if not all_resources:
resources_type = form.cleaned_data.get('type')
aux = []
for resource_name in resources_type.split(','):
if resource_name in resources:
aux.append(resource_name)
resources=aux
queryset = FinderQuerySet(FinderManager(HomeFinder),
category_filters= category_filters,
query=query,
resource=resources,
max_results=250,
order=order_elastic,
reverse = reverse,
account_id=account.id
)
paginator = Paginator(queryset, 25)
revisions = paginator.page(page and page or 1)
if data['federated_accounts_ids']:
add_domains_to_permalinks(revisions.object_list)
error = ''
results = revisions.object_list
else:
error = 'Invalid data'
results=[]
categories=[]
t = loader.get_template('loadHome/table.json')
c = Context(locals())
return HttpResponse(t.render(c), content_type="application/json")
0
Example 61
Project: edx-platform Source File: migrate.py
def manage_modulestores(request, reload_dir=None, commit_id=None):
'''
Manage the static in-memory modulestores.
If reload_dir is not None, then instruct the xml loader to reload that course directory.
'''
html = "<html><body>"
def_ms = modulestore()
courses = def_ms.get_courses()
#----------------------------------------
# check on IP address of requester
ip = getip(request)
if LOCAL_DEBUG:
html += '<h3>IP address: %s <h3>' % ip
html += '<h3>User: %s </h3>' % request.user
html += '<h3>My pid: %s</h3>' % os.getpid()
log.debug(u'request from ip=%s, user=%s', ip, request.user)
if not (ip in ALLOWED_IPS or 'any' in ALLOWED_IPS):
if request.user and request.user.is_staff:
log.debug(u'request allowed because user=%s is staff', request.user)
else:
html += 'Permission denied'
html += "</body></html>"
log.debug('request denied, ALLOWED_IPS=%s', ALLOWED_IPS)
return HttpResponse(html, status=403)
#----------------------------------------
# reload course if specified; handle optional commit_id
if reload_dir is not None:
if reload_dir not in def_ms.courses:
html += '<h2 class="inline-error">Error: "%s" is not a valid course directory</h2>' % reload_dir
else:
# reloading based on commit_id is needed when running mutiple worker threads,
# so that a given thread doesn't reload the same commit multiple times
current_commit_id = get_commit_id(def_ms.courses[reload_dir])
log.debug('commit_id="%s"', commit_id)
log.debug('current_commit_id="%s"', current_commit_id)
if (commit_id is not None) and (commit_id == current_commit_id):
html += "<h2>Already at commit id %s for %s</h2>" % (commit_id, reload_dir)
track.views.server_track(request,
'reload %s skipped already at %s (pid=%s)' % (reload_dir,
commit_id,
os.getpid(),
),
{}, page='migrate')
else:
html += '<h2>Reloaded course directory "%s"</h2>' % reload_dir
def_ms.try_load_course(reload_dir)
gdir = settings.DATA_DIR / reload_dir
new_commit_id = os.popen('cd %s; git log -n 1 | head -1' % gdir).read().strip().split(' ')[1]
set_commit_id(def_ms.courses[reload_dir], new_commit_id)
html += '<p>commit_id=%s</p>' % new_commit_id
track.views.server_track(request, 'reloaded %s now at %s (pid=%s)' % (reload_dir,
new_commit_id,
os.getpid()), {}, page='migrate')
#----------------------------------------
html += '<h2>Courses loaded in the modulestore</h2>'
html += '<ol>'
for cdir, course in def_ms.courses.items():
html += '<li><a href="%s/migrate/reload/%s">%s</a> (%s)</li>' % (
settings.EDX_ROOT_URL,
escape(cdir),
escape(cdir),
course.location.to_deprecated_string()
)
html += '</ol>'
#----------------------------------------
#dumpfields = ['definition', 'location', 'metadata']
dumpfields = ['location', 'metadata']
for cdir, course in def_ms.courses.items():
html += '<hr width="100%"/>'
html += '<h2>Course: %s (%s)</h2>' % (course.display_name_with_default_escaped, cdir)
html += '<p>commit_id=%s</p>' % get_commit_id(course)
for field in dumpfields:
data = getattr(course, field, None)
html += '<h3>%s</h3>' % field
if isinstance(data, dict):
html += '<ul>'
for k, v in data.items():
html += '<li>%s:%s</li>' % (escape(k), escape(v))
html += '</ul>'
else:
html += '<ul><li>%s</li></ul>' % escape(data)
#----------------------------------------
html += '<hr width="100%"/>'
html += "courses: <pre>%s</pre>" % escape(courses)
ms = xmodule_django._MODULESTORES
html += "modules: <pre>%s</pre>" % escape(ms)
html += "default modulestore: <pre>%s</pre>" % escape(unicode(def_ms))
#----------------------------------------
log.debug('_MODULESTORES=%s', ms)
log.debug('courses=%s', courses)
log.debug('def_ms=%s', unicode(def_ms))
html += "</body></html>"
return HttpResponse(html)
0
Example 62
Project: AuShadha Source File: views.py
@login_required
def social_history_add(request, patient_id = None):
if request.user:
user = request.user
try:
if patient_id:
patient_id = int(patient_id)
else:
patient_id = int(request.GET.get('patient_id'))
patient_detail_obj = PatientDetail.objects.get(pk=patient_id)
#patient_detail_obj.generate_urls()
if not getattr(patient_detail_obj, 'urls',None):
patient_detail_obj.save()
social_history_obj = SocialHistory.objects.filter(patient_detail=patient_detail_obj)
if social_history_obj:
return social_history_edit(request, social_history_obj[0].id)
else:
social_history_obj = SocialHistory(patient_detail=patient_detail_obj)
if request.method == "GET" and request.is_ajax():
social_history_form = SocialHistoryForm(instance=social_history_obj)
variable = RequestContext(request,
{"user": user,
"patient_detail_obj": patient_detail_obj,
"social_history_form": social_history_form,
"social_history_obj": social_history_obj,
'button_label': "Add",
"action": patient_detail_obj.urls['add']['social_history'],
"addUrl": patient_detail_obj.urls['add']['social_history'],
'canDel': False,
'editUrl': None,
'delUrl': None
})
return render_to_response('social_history/add_or_edit_form.html', variable)
elif request.method == 'POST' and request.is_ajax():
copy_post = request.POST.copy()
#print "Received POST Request with", request.POST
#print "Home Occupants received are", copy_post.getlist('home_occupants')
copy_post['home_occupants'] = ",".join(copy_post.getlist('home_occupants'))
copy_post['pets'] = ",".join(copy_post.getlist('pets'))
social_history_form = SocialHistoryForm(copy_post, instance=social_history_obj)
if social_history_form.is_valid():
try:
social_history_obj = social_history_form.save()
success = True
error_message = "SocialHistory Data Added Successfully"
form_errors = None
addData = {
"marital_status": social_history_obj.marital_status,
"marital_status_notes": social_history_obj.marital_status_notes,
"occupation": social_history_obj.occupation,
"occupation_notes": social_history_obj.occupation_notes,
"exercise": social_history_obj.exercise,
"exercise_notes": social_history_obj.exercise_notes,
"diet": social_history_obj.diet,
"diet_notes": social_history_obj.diet_notes,
"home_occupants": social_history_obj.home_occupants,
"home_occupants_notes": social_history_obj.home_occupants_notes,
"pets": social_history_obj.pets,
"pets_notes": social_history_obj.pets_notes,
"alcohol": social_history_obj.alcohol,
"alcohol_no": social_history_obj.alcohol_no,
"alcohol_notes": social_history_obj.alcohol_notes,
"tobacco": social_history_obj.tobacco,
"tobacco_no": social_history_obj.tobacco_no,
"tobacco_notes": social_history_obj.tobacco_notes,
"drug_abuse": social_history_obj.drug_abuse,
"drug_abuse_notes": social_history_obj.drug_abuse_notes,
"sexual_preference": social_history_obj.sexual_preference,
"sexual_preference_notes": social_history_obj.sexual_preference_notes,
"current_events": social_history_obj.current_events
}
if not hasattr(social_history_obj,'urls'):
social_history_obj.save()
urls = social_history_obj.urls
data = {'success': success,
'error_message': error_message,
'form_errors': form_errors,
'canDel': True,
'addUrl': None,
"addData": addData,
'editUrl': social_history_obj.urls['edit'],
'delUrl': social_history_obj.urls['del'],
}
except (Exception("SocialHistoryExistsError")):
data = {'success': False,
'error_message': "Social History Already Exists ! Cannot add More",
'form_errors': error_message,
'addData':None
}
else:
error_message = aumodelformerrorformatter_factory(social_history_form)
data = {'success': False,
'error_message': error_message,
'form_errors': error_message,
'addData':None
}
jsondata = json.dumps(data)
return HttpResponse(jsondata, content_type='application/json')
else:
raise Http404(
"BadRequest: Unsupported Request Method. AJAX status is:: " + unicode(request.is_ajax()))
except TypeError or ValueError or AttributeError:
raise Http404("BadRequest")
except (PatientDetail.DoesNotExist):
raise Http404("BadRequest: Patient Data Does Not Exist")
0
Example 63
Project: commcare-hq Source File: object_fetch_api.py
@method_decorator(login_or_digest_or_basic_or_apikey())
def get(self, request, domain, case_id=None, attachment_id=None):
"""
https://github.com/dimagi/commcare/wiki/CaseAttachmentAPI
max_size The largest size (in bytes) for the attachment
max_image_width The largest width in pixels for an an image attachment
max_image_height The largest width in pixels for an an image attachment
"""
if self.request.couch_user.is_web_user() and not can_view_attachments(self.request):
return HttpResponseForbidden()
if not case_id or not attachment_id:
raise Http404
img = self.request.GET.get('img', None)
size = self.request.GET.get('size', OBJECT_ORIGINAL)
max_width = int(self.request.GET.get('max_image_width', 0))
max_height = int(self.request.GET.get('max_image_height', 0))
max_filesize = int(self.request.GET.get('max_size', 0))
try:
CaseAccessors(domain).get_case(case_id)
except CaseNotFound:
raise Http404
if img is not None:
if size == "debug_all":
url_base = reverse("api_case_attachment", kwargs={
"domain": self.request.domain,
"case_id": case_id,
"attachment_id": attachment_id,
})
r = HttpResponse(content_type="text/html")
r.write('<html><body>')
r.write('<ul>')
for fsize in IMAGE_SIZE_ORDERING:
meta, stream = fetch_case_image(
domain,
case_id,
attachment_id,
filesize_limit=max_filesize,
width_limit=max_width,
height_limit=max_height,
fixed_size=fsize
)
r.write('<li>')
r.write('Size: %s<br>' % fsize)
r.write("Limit: max_size: %s" % max_filesize)
if max_width > 0:
r.write(", max_width: %s" % max_width)
if max_height > 0:
r.write(", max_height: %s" % max_height)
r.write("<br>")
if meta is not None:
r.write('Resolution: %d x %d<br>' % (meta['width'], meta['height']))
r.write('Filesize: %d<br>' % meta['content_length'])
url_params = urllib.urlencode({
"img": '1',
"size": fsize,
"max_size": max_filesize,
"max_image_width": max_width,
"max_image_height": max_height
})
r.write('<img src="%(attach_url)s?%(params)s">' % {
"attach_url": url_base,
"params": url_params
})
else:
r.write('Not available')
r.write('</li>')
r.write('</ul></body></html>')
return r
else:
attachment_meta, attachment_stream = fetch_case_image(
domain,
case_id,
attachment_id,
filesize_limit=max_filesize,
width_limit=max_width,
height_limit=max_height,
fixed_size=size
)
else:
cached_attachment = get_cached_case_attachment(domain, case_id, attachment_id)
attachment_meta, attachment_stream = cached_attachment.get()
if attachment_meta is not None:
mime_type = attachment_meta['content_type']
else:
mime_type = "plain/text"
return StreamingHttpResponse(streaming_content=FileWrapper(attachment_stream),
content_type=mime_type)
0
Example 64
Project: eve-wspace Source File: views.py
@login_required
def add_pos(request, msID):
"""
GET gets the add POS dialog, POST processes it.
"""
if not request.is_ajax():
raise PermissionDenied
mapsystem = get_object_or_404(MapSystem, pk=msID)
system = get_object_or_404(System, pk=mapsystem.system.pk)
if request.method == 'POST':
corp_name = request.POST.get('corp', None)
if not corp_name:
return HttpResponse('Corp cannot be blank!', status=400)
try:
corp = Corporation.objects.get(name=corp_name)
except Corporation.DoesNotExist:
# Corp isn't in our DB, get its ID and add it
try:
api = eveapi.EVEAPIConnection(cacheHandler=handler)
corp_id = (api.eve.CharacterID(names=corp_name)
.characters[0].characterID)
if corp_id == 0:
return HttpResponse('Corp does not exist!', status=404)
corp = core_tasks.update_corporation(corp_id, True)
except:
# Error while talking to the EVE API
return HttpResponse('Could not verify Corp name. Please try again later.', status=404)
else:
# Have the async worker update the corp so that it is up to date
core_tasks.update_corporation.delay(corp.id)
if request.POST['auto'] == '1':
fittings = []
moon_distance = 150000000
for i in request.POST['fitting'].splitlines():
cols = i.split('\t')
# ignore offgrid stuff
if cols[2] != '-':
fittings.append(cols)
if cols[1] == 'Moon' and cols[2].endswith('km'):
# found a moon close by
distance = int(cols[2][:-3].replace(',', '')
.replace('.', '').replace(u'\xa0', ''))
if distance < moon_distance:
# closest moon so far
moon_distance = distance
moon_name = cols[0]
if moon_distance == 150000000:
# No moon found
return HttpResponse('No moon found in d-scan!', status=404)
# parse POS location
regex = '^%s ([IVX]+) - Moon ([0-9]+)$' % (system.name,)
re_result = re.match(regex, moon_name)
if not re_result:
return HttpResponse(
'Invalid D-Scan! Do you have the right system?',
status=400)
else:
result = re_result.groups()
NUMERALS = {'X': 10, 'V': 5, 'I': 1}
planet = 0
for i in range(len(result[0])):
value = NUMERALS[result[0][i]]
try:
next_value = NUMERALS[result[0][i+1]]
except IndexError:
next_value = 0
if value < next_value:
planet -= value
else:
planet += value
moon = int(result[1])
pos = POS(system=system, planet=planet,
moon=moon, status=int(request.POST['status']),
corporation=corp)
try:
pos.fit_from_iterable(fittings)
except AttributeError as e:
return HttpResponse(e, status=404)
else:
tower = get_object_or_404(Type, name=request.POST['tower'], marketgroup__isnull=False)
pos = POS(system=system, planet=int(request.POST['planet']),
moon=int(request.POST['moon']),
towertype=tower,
posname=request.POST['name'],
fitting=request.POST['fitting'],
status=int(request.POST['status']),
corporation=corp)
if request.POST.get('dscan', None) == "1":
pos.fit_from_dscan(request.POST['fitting'].encode('utf-8'))
if pos.status == 3:
if request.POST['rfdays'] == '':
rf_days = 0
else:
rf_days = int(request.POST['rfdays'])
if request.POST['rfhours'] == '':
rf_hours = 0
else:
rf_hours = int(request.POST['rfhours'])
if request.POST['rfminutes'] == '':
rf_minutes = 0
else:
rf_minutes = int(request.POST['rfminutes'])
delta = timedelta(days=rf_days,
hours=rf_hours,
minutes=rf_minutes)
pos.rftime = datetime.now(pytz.utc) + delta
pos.log(request.user, "Added", mapsystem)
pos.save()
return HttpResponse()
else:
return TemplateResponse(request, 'add_pos.html', {'system': system, 'mapsystem': mapsystem})
0
Example 65
Project: crowdsource-platform Source File: project.py
@detail_route(methods=['get'], url_path='sample-script')
def sample_script(self, request, *args, **kwargs):
project = self.get_object()
template_items = project.template.items.all()
tokens = []
output = {}
for item in template_items:
aux_attrib = item.aux_attributes
if 'src' in aux_attrib:
tokens += get_template_tokens(aux_attrib['src'])
if 'question' in aux_attrib:
tokens += get_template_tokens(aux_attrib['question']['value'])
if 'options' in aux_attrib:
for option in aux_attrib['options']:
tokens += get_template_tokens(option['value'])
if item.role == models.TemplateItem.ROLE_INPUT:
output["'%s'" % item.name] = "response.get('fields').get('%s')" % item.name
data = {}
input = {}
for token in tokens:
data[token] = "value"
input["'%s'" % token] = "response.get('task_data').get('%s')" % token
hash_id = ProjectSerializer.get_hash_id(project)
task_data = json.dumps([data], indent=4, separators=(',', ': '))
task_input = json.dumps(input, indent=4, separators=(',', ': ')).replace('\"', '')
task_output = json.dumps(output, indent=4, separators=(',', ': ')).replace('\"', '')
sandbox = ""
sandbox_import = ""
if settings.IS_SANDBOX:
sandbox = ", host=SANDBOX"
sandbox_import = "from daemo.constants import SANDBOX"
script = \
"""
%s
from daemo.client import DaemoClient
# Remember any task launched under this rerun key, so you can debug or resume the by re-running
RERUN_KEY = 'myfirstrun'
# The key for your project, copy-pasted from the project editing page
PROJECT_KEY='%s'
# If your project has inputs, send them as dicts
# to the publish() call. Daemo will publish a
# task for each item in the list
task_data = %s
# Create the client
client = DaemoClient(rerun_key=RERUN_KEY%s)
def approve(worker_responses):
\"\"\"
The approve callback is called when work is complete; it receives
a list of worker responses. Return a list of True (approve) and
False (reject) values. Approved tasks are passed on to the
completed callback, and rejected tasks are automatically relaunched.
\"\"\"
approvals = [True] * len(worker_responses)
for count, response in enumerate(worker_responses):
task_input = %s
task_output = %s
# TODO write your approve function here
# approvals[count] = True or False
return approvals
def completed(worker_responses):
\"\"\"
Once tasks are approved, the completed callback is sent a list of
final approved worker responses. Perform any computation that you
want on the results. Don't forget to send Daemo the rating scores
so that it can improve and find better workers next time.
\"\"\"
# TODO write your completed function here
# ratings = [{
# \"task_id\": response.get(\"task_id\"),
# \"worker_id\": response.get(\"worker_id\"),
# \"weight\": <<WRITE RATING FUNCTION HERE>> }
# for response in worker_responses]
client.rate(project_key=PROJECT_KEY, ratings=ratings)
# Publish the tasks
client.publish(
project_key=PROJECT_KEY,
tasks=task_data,
approve=approve,
completed=completed
)
"""
response = HttpResponse(content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename="daemo_script.py"'
final_script = dedent(script) % (sandbox_import, hash_id, task_data, sandbox, task_input, task_output)
response.content, _ = FormatCode(final_script, verify=False)
return response
0
Example 66
Project: image Source File: views.py
def image(request, path, token, autogen=False):
is_admin = False
if ("is_admin=true" in token and request and request.user.has_perm('admin')) or autogen:
parameters = token
is_admin = True
if autogen:
token = image_create_token(parameters)
else:
parameters = request.session.get(token, token)
cached_image_file = os.path.join(path, token)
now = timezone.now()
expire_offset = timezone.timedelta(seconds=IMAGE_CACHE_HTTP_EXPIRATION)
response = HttpResponse()
response['Content-type'] = 'image/jpeg'
response['Expires'] = (now + expire_offset).strftime("%a, %d %b %Y %T GMT")
response['Last-Modified'] = now.strftime("%a, %d %b %Y %T GMT")
response['Cache-Control'] = 'max-age=3600, must-revalidate'
response.status_code = 200
# If we already have the cache we send it instead of recreating it
if IMAGE_CACHE_STORAGE.exists(cached_image_file):
if autogen:
return 'Already generated'
try:
f = IMAGE_CACHE_STORAGE.open(cached_image_file, "rb")
except IOError:
raise Http404()
response.write(f.read())
f.close()
response['Last-Modified'] = IMAGE_CACHE_STORAGE.modified_time(cached_image_file).strftime("%a, %d %b %Y %T GMT")
return response
if parameters == token and not is_admin:
return HttpResponse("Forbidden", status=403)
qs = QueryDict(parameters)
file_storage = MEDIA_STORAGE
if qs.get('static', '') == "true":
file_storage = STATIC_STORAGE
format = qs.get('format', IMAGE_DEFAULT_FORMAT)
quality = int(qs.get('quality', IMAGE_DEFAULT_QUALITY))
mask = qs.get('mask', None)
mask_source = qs.get('mask_source', None)
if mask is not None:
format = "PNG"
fill = qs.get('fill', None)
background = qs.get('background', None)
tint = qs.get('tint', None)
center = qs.get('center', ".5,.5")
mode = qs.get('mode', "crop")
enlarge = qs.get('enlarge', "true")
overlays = qs.getlist('overlay')
overlay_sources = qs.getlist('overlay_source')
overlay_tints = qs.getlist('overlay_tint')
overlay_sizes = qs.getlist('overlay_size')
overlay_positions = qs.getlist('overlay_position')
width = qs.get('width', None)
if width:
width = int(width)
height = qs.get('height', None)
if height:
height = int(height)
pre_rotation = qs.get('pre_rotation', None)
post_rotation = qs.get('post_rotation', None)
try:
padding = float(qs.get('padding', None))
except TypeError:
padding = 0.0
grayscale = bool(qs.get('grayscale', False))
if "video" in qs:
data, http_response = generate_thumb(file_storage, force_text(path))
response.status_code = http_response
else:
try:
try:
f = requests.get(qs['url'])
data = f.content
f.close()
except KeyError:
f = file_storage.open(path)
data = f.read()
f.close()
except IOError:
response.status_code = 404
data = ""
if data:
try:
crop = (mode != "scale")
force = (enlarge == "true")
output_data = render(data, width, height, force=force, padding=padding, overlays=overlays,
overlay_sources=overlay_sources, overlay_tints=overlay_tints,
overlay_positions=overlay_positions, overlay_sizes=overlay_sizes, mask=mask,
mask_source=mask_source, center=center, format=format, quality=quality, fill=fill,
background=background, tint=tint, pre_rotation=pre_rotation,
post_rotation=post_rotation, crop=crop, grayscale=grayscale)
except IOError:
traceback.print_exc()
response.status_code = 500
output_data = ""
else:
output_data = data
if response.status_code == 200:
IMAGE_CACHE_STORAGE.save(cached_image_file, ContentFile(output_data))
if autogen:
return 'Generated ' + six.text_type(response.status_code)
else:
if autogen:
return 'Failed ' + cached_image_file
response.write(output_data)
return response
0
Example 67
@csrf_exempt
def ajax_upload(request, folder_id=None):
"""
Receives an upload from the uploader. Receives only one file at a time.
"""
mimetype = "application/json" if request.is_ajax() else "text/html"
content_type_key = 'mimetype' if LTE_DJANGO_1_4 else 'content_type'
response_params = {content_type_key: mimetype}
folder = None
if folder_id:
try:
# Get folder
folder = Folder.objects.get(pk=folder_id)
except Folder.DoesNotExist:
return HttpResponse(json.dumps({'error': NO_FOLDER_ERROR}),
**response_params)
# check permissions
if folder and not folder.has_add_children_permission(request):
return HttpResponse(
json.dumps({'error': NO_PERMISSIONS_FOR_FOLDER}),
**response_params)
try:
if len(request.FILES) == 1:
# dont check if request is ajax or not, just grab the file
upload, filename, is_raw = handle_request_files_upload(request)
else:
# else process the request as usual
upload, filename, is_raw = handle_upload(request)
# TODO: Deprecated/refactor
# Get clipboad
# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]
# find the file type
for filer_class in filer_settings.FILER_FILE_MODELS:
FileSubClass = load_object(filer_class)
# TODO: What if there are more than one that qualify?
if FileSubClass.matches_file_type(filename, upload, request):
FileForm = modelform_factory(
model=FileSubClass,
fields=('original_filename', 'owner', 'file')
)
break
uploadform = FileForm({'original_filename': filename,
'owner': request.user.pk},
{'file': upload})
if uploadform.is_valid():
file_obj = uploadform.save(commit=False)
# Enforce the FILER_IS_PUBLIC_DEFAULT
file_obj.is_public = filer_settings.FILER_IS_PUBLIC_DEFAULT
file_obj.folder = folder
file_obj.save()
# TODO: Deprecated/refactor
# clipboard_item = ClipboardItem(
# clipboard=clipboard, file=file_obj)
# clipboard_item.save()
# Try to generate thumbnails.
if not file_obj.icons:
# There is no point to continue, as we can't generate
# thumbnails for this file. Usual reasons: bad format or
# filename.
file_obj.delete()
# This would be logged in BaseImage._generate_thumbnails()
# if FILER_ENABLE_LOGGING is on.
return HttpResponse(
json.dumps(
{'error': 'failed to generate icons for file'}),
status=500,
**response_params)
thumbnail = None
# Backwards compatibility: try to get specific icon size (32px)
# first. Then try medium icon size (they are already sorted),
# fallback to the first (smallest) configured icon.
for size in (['32'] +
filer_settings.FILER_ADMIN_ICON_SIZES[1::-1]):
try:
thumbnail = file_obj.icons[size]
break
except KeyError:
continue
json_response = {
'thumbnail': thumbnail,
'alt_text': '',
'label': str(file_obj),
'file_id': file_obj.pk,
}
# prepare preview thumbnail
if type(file_obj) == Image:
thumbnail_180_options = {
'size': (180, 180),
'crop': True,
'upscale': True,
}
thumbnail_180 = file_obj.file.get_thumbnail(
thumbnail_180_options)
json_response['thumbnail_180'] = thumbnail_180.url
json_response['original_image'] = file_obj.url
return HttpResponse(json.dumps(json_response),
**response_params)
else:
form_errors = '; '.join(['%s: %s' % (
field,
', '.join(errors)) for field, errors in list(
uploadform.errors.items())
])
raise UploadException(
"AJAX request not valid: form invalid '%s'" % (
form_errors,))
except UploadException as e:
return HttpResponse(json.dumps({'error': str(e)}),
status=500,
**response_params)
0
Example 68
Project: geonode Source File: views.py
def new_map_config(request):
'''
View that creates a new map.
If the query argument 'copy' is given, the initial map is
a copy of the map with the id specified, otherwise the
default map configuration is used. If copy is specified
and the map specified does not exist a 404 is returned.
'''
DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config()
if request.method == 'GET' and 'copy' in request.GET:
mapid = request.GET['copy']
map_obj = _resolve_map(request, mapid, 'base.view_resourcebase')
map_obj.abstract = DEFAULT_ABSTRACT
map_obj.title = DEFAULT_TITLE
if request.user.is_authenticated():
map_obj.owner = request.user
config = map_obj.viewer_json(request.user)
del config['id']
else:
if request.method == 'GET':
params = request.GET
elif request.method == 'POST':
params = request.POST
else:
return HttpResponse(status=405)
if 'layer' in params:
bbox = None
map_obj = Map(projection=getattr(settings, 'DEFAULT_MAP_CRS',
'EPSG:900913'))
layers = []
for layer_name in params.getlist('layer'):
try:
layer = _resolve_layer(request, layer_name)
except ObjectDoesNotExist:
# bad layer, skip
continue
if not request.user.has_perm(
'view_resourcebase',
obj=layer.get_self_resource()):
# invisible layer, skip inclusion
continue
layer_bbox = layer.bbox
# assert False, str(layer_bbox)
if bbox is None:
bbox = list(layer_bbox[0:4])
else:
bbox[0] = min(bbox[0], layer_bbox[0])
bbox[1] = max(bbox[1], layer_bbox[1])
bbox[2] = min(bbox[2], layer_bbox[2])
bbox[3] = max(bbox[3], layer_bbox[3])
config = layer.attribute_config()
# Add required parameters for GXP lazy-loading
config["title"] = layer.title
config["queryable"] = True
config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
else llbbox_to_mercator([float(coord) for coord in bbox])
if layer.storeType == "remoteStore":
service = layer.service
maplayer = MapLayer(map=map_obj,
name=layer.typename,
ows_url=layer.ows_url,
layer_params=json.dumps(config),
visibility=True,
source_params=json.dumps({
"ptype": service.ptype,
"remote": True,
"url": service.base_url,
"name": service.name}))
else:
maplayer = MapLayer(
map=map_obj,
name=layer.typename,
ows_url=layer.ows_url,
# use DjangoJSONEncoder to handle Decimal values
layer_params=json.dumps(config, cls=DjangoJSONEncoder),
visibility=True
)
layers.append(maplayer)
if bbox is not None:
minx, miny, maxx, maxy = [float(c) for c in bbox]
x = (minx + maxx) / 2
y = (miny + maxy) / 2
if getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913') == "EPSG:4326":
center = list((x, y))
else:
center = list(forward_mercator((x, y)))
if center[1] == float('-inf'):
center[1] = 0
BBOX_DIFFERENCE_THRESHOLD = 1e-5
# Check if the bbox is invalid
valid_x = (maxx - minx) ** 2 > BBOX_DIFFERENCE_THRESHOLD
valid_y = (maxy - miny) ** 2 > BBOX_DIFFERENCE_THRESHOLD
if valid_x:
width_zoom = math.log(360 / abs(maxx - minx), 2)
else:
width_zoom = 15
if valid_y:
height_zoom = math.log(360 / abs(maxy - miny), 2)
else:
height_zoom = 15
map_obj.center_x = center[0]
map_obj.center_y = center[1]
map_obj.zoom = math.ceil(min(width_zoom, height_zoom))
config = map_obj.viewer_json(
request.user, *(DEFAULT_BASE_LAYERS + layers))
config['fromLayer'] = True
else:
config = DEFAULT_MAP_CONFIG
return json.dumps(config)
0
Example 69
Project: Adlibre-DMS Source File: views.py
@login_required
@group_required(SEC_GROUP_NAMES['index'])
def indexing_source(request, step=None, template='mdtui/indexing.html'):
"""Indexing: Step 3: Upload File / Associate File / Print Barcode
@param request: is a Django request object
@param step: is a current step name (for template rendering)
@param template: is a name of template for this view"""
context = {}
warnings = []
valid_call = True
temp_vars = {}
upload_file = None
# Check session variables, init context and add proper user warnings
for var_name, context_var, action in [
('docuement_keys', "docuement_keys_dict", 'NO_INDEX'),
('barcode', 'barcode', 'NO_INDEX'),
('index_info', 'docuement_keys_dict', 'NO_S_KEYS'),
('docrule', 'indexing_docrule_id', 'NO_DOCRULE'),
]:
try:
temp_vars[var_name] = None # Make sure it will definitely be there (Proper init)
temp_var = request.session[context_var]
temp_vars[var_name] = temp_var
except KeyError:
valid_call = False
if not MDTUI_ERROR_STRINGS[action] in warnings:
warnings.append(MDTUI_ERROR_STRINGS[action])
docuement_keys = temp_vars['docuement_keys']
barcode = temp_vars['barcode']
index_info = temp_vars['index_info']
docrule = str(temp_vars['docrule'])
# Init Forms correctly depending on url posted
if request.GET.get('uploaded') is None:
upload_form = DocuementUploadForm()
else:
upload_form = DocuementUploadForm(request.POST or None, request.FILES or None)
if request.GET.get('barcoded') is None:
barcode_form = BarcodePrintedForm()
else:
barcode_form = BarcodePrintedForm(request.POST or None)
log.debug('indexing_source view called with docuement_keys: %s, barcode: %s, index_info: %s, docrule: %s' %
(docuement_keys, barcode, index_info, docrule))
# Appending warnings for creating a new parrallel key/value pair.
new_sec_key_pairs = check_for_secondary_keys_pairs(index_info, docrule)
if new_sec_key_pairs:
for new_key, new_value in new_sec_key_pairs.iteritems():
warnings.append(MDTUI_ERROR_STRINGS['NEW_KEY_VALUE_PAIR'] + new_key + ': ' + new_value)
if upload_form.is_valid() or barcode_form.is_valid() and valid_call:
if valid_call:
# Unifying dates to CouchDB storage formats.
# TODO: maybe make it a part of the CouchDB storing manager.
clean_index = unify_index_info_couch_dates_fmt(index_info)
# Storing into DMS with main Docuement Processor and current indexes
processor = DocuementProcessor()
options = {
'user': request.user,
'index_info': clean_index,
'barcode': barcode,
}
if upload_form.is_valid():
upload_file = upload_form.files['file']
else:
options['only_metadata'] = True
processor.create(upload_file, options)
if not processor.errors:
if 'only_metadata' in options and options['only_metadata'] is not None:
# For silent barcode storage in MUI
return HttpResponse('OK')
return HttpResponseRedirect(reverse('mdtui-index-finished'))
else:
# FIXME: dodgy error handling
log.error(str(processor.errors))
return HttpResponse(str(processor.errors))
else:
warnings.append(MDTUI_ERROR_STRINGS['NOT_VALID_INDEXING'])
context.update({
'step': step,
'valid_call': valid_call,
'upload_form': upload_form,
'barcode_form': barcode_form,
'docuement_keys': docuement_keys,
'warnings': warnings,
'barcode': barcode,
})
return render_to_response(template, context, context_instance=RequestContext(request))
0
Example 70
Project: ganetimgr Source File: instances.py
@login_required
def user_sum_stats(request):
if request.user.is_anonymous():
action = {
'error': _(
"Permissions' violation. This action has been"
" logged and our admins will be notified about it"
)
}
return HttpResponse(json.dumps(action), mimetype='application/json')
p = Pool(20)
instances = []
bad_clusters = []
def _get_instances(cluster):
try:
instances.extend(cluster.get_user_instances(request.user))
except GanetiApiError as e:
bad_clusters.append((cluster, format_ganeti_api_error(e)))
except Exception as e:
bad_clusters.append((cluster, e))
finally:
close_connection()
if not request.user.is_anonymous():
# get only enabled clusters
p.map(_get_instances, Cluster.objects.filter(disabled=False))
if bad_clusters:
for c in bad_clusters:
if request.user.is_superuser:
djmessages.add_message(
request,
msgs.WARNING,
"Some instances may be missing because the following clusters are unreachable: %s" % (
", ".join(
[
"%s: %s" % (
c[0].slug or c[0].hostname,
c[1]
)
]
)
)
)
else:
djmessages.add_message(
request,
msgs.WARNING,
"Some instances may be missing because the following clusters are unreachable: %s" % (
", ".join(
[
"%s" % (
c[0].slug or c[0].hostname,
)
]
)
)
)
jresp = {}
cache_key = "user:%s:index:instance:light" % request.user.username
res = cache.get(cache_key)
instancedetails = []
j = Pool(80)
user = request.user
def _get_instance_details(instance):
try:
instancedetails.extend(generate_json_light(instance, user))
except (GanetiApiError, Exception):
pass
finally:
close_connection()
if res is None:
j.map(_get_instance_details, instances)
jresp['aaData'] = instancedetails
cache.set(cache_key, jresp, 125)
res = jresp
instances_stats = []
user_dict = {}
cache_key_stats = "user:%s:index:users:instance:stats" % \
request.user.username
instances_stats = cache.get(cache_key_stats)
if instances_stats is None:
for i in res['aaData']:
if not 'users' in i:
i['users'] = [{'user': request.user.username}]
for useritem in i['users']:
if not useritem['user'] in user_dict:
user_dict[useritem['user']] = {
'instances': 0,
'disk': 0,
'cpu': 0,
'memory': 0
}
user_dict[useritem['user']]['instances'] = user_dict[
useritem['user']
]['instances'] + 1
user_dict[useritem['user']]['disk'] = user_dict[
useritem['user']
]['disk'] + int(i['disk'])
user_dict[useritem['user']]['cpu'] = user_dict[
useritem['user']
]['cpu'] + int(i['vcpus'])
user_dict[useritem['user']]['memory'] = user_dict[
useritem['user']
]['memory'] + int(i['memory'])
#TODO: Must implement that in a more efficient way
instances_stats_list = []
for u in user_dict.keys():
user_stats_dict = {}
user_stats_dict['user_href'] = '%s' % (
reverse(
'user-info',
kwargs={
'type': 'user',
'usergroup': u
}
)
)
user_stats_dict['user'] = u
user_stats_dict['instances'] = user_dict[u]['instances']
user_stats_dict['disk'] = user_dict[u]['disk']
user_stats_dict['cpu'] = user_dict[u]['cpu']
user_stats_dict['memory'] = user_dict[u]['memory']
instances_stats_list.append(user_stats_dict)
return_dict = {'aaData': instances_stats_list}
cache.set(cache_key_stats, return_dict, 300)
instances_stats = return_dict
return HttpResponse(
json.dumps(instances_stats),
mimetype='application/json'
)
0
Example 71
Project: satchmo Source File: forms.py
def export(self, request):
self.full_clean()
format = 'yaml'
selected = []
include_images = False
include_categories = False
for name, value in self.cleaned_data.items():
if name == 'format':
format = value
continue
if name == 'include_images':
include_images = value
continue
if name == 'include_categories':
include_categories = value
continue
opt, key = name.split('__')
if opt=='export':
if value:
selected.append(key)
try:
serializers.get_serializer(format)
except KeyError:
raise CommandError("Unknown serialization format: %s" % format)
objects = []
images = []
categories = {}
for slug in selected:
product = Product.objects.get(slug=slug)
objects.append(product)
for subtype in product.get_subtypes():
objects.append(getattr(product,subtype.lower()))
objects.extend(list(product.price_set.all()))
objects.extend(list(product.productimage_set.all()))
if include_images:
for image in product.productimage_set.all():
images.append(image.picture)
if include_categories:
for category in product.category.all():
if category not in categories:
categories[category] = 1
# Export all categories, translations. Export images,translations if
# desired.
if include_categories:
for category in categories.keys():
objects.append(category)
objects.extend(list(category.translations.all()))
if include_images:
for image in category.images.all():
objects.append(image)
objects.extend(list(image.translations.all()))
try:
raw = serializers.serialize(format, objects, indent=False)
except Exception, e:
raise CommandError("Unable to serialize database: %s" % e)
if include_images:
filedir = settings.MEDIA_ROOT
buf = StringIO()
zf = zipfile.ZipFile(buf, 'a', zipfile.ZIP_STORED)
export_file = 'products.%s' % format
zf.writestr(str(export_file), raw)
zinfo = zf.getinfo(str(export_file))
# Caution, highly magic number, chmods the file to 644
zinfo.external_attr = 2175008768L
image_dir = config_value('PRODUCT', 'IMAGE_DIR')
config = "PRODUCT.IMAGE_DIR=%s\nEXPORT_FILE=%s" % (image_dir, export_file)
zf.writestr('VARS', config)
zinfo = zf.getinfo('VARS')
# Caution, highly magic number, chmods the file to 644
zinfo.external_attr = 2175008768L
for image in images:
f = os.path.join(filedir, image)
if os.path.exists(f):
zf.write(f, str(image))
zf.close()
raw = buf.getvalue()
mimetype = "application/zip"
format = "zip"
else:
mimetype = "text/" + format
response = HttpResponse(mimetype=mimetype, content=raw)
response['Content-Disposition'] = 'attachment; filename="products-%s.%s"' % (time.strftime('%Y%m%d-%H%M'), format)
return response
0
Example 72
Project: Mobile-Security-Framework-MobSF Source File: shared_func.py
def PDF(request):
try:
MD5 = request.GET['md5']
TYP = request.GET['type']
m = re.match('^[0-9a-f]{32}$', MD5)
if m:
if TYP in ['APK', 'ANDZIP']:
DB = StaticAnalyzerAndroid.objects.filter(MD5=MD5)
if DB.exists():
print "\n[INFO] Fetching data from DB for PDF Report Generation (Android)"
context = {
'title': DB[0].TITLE,
'name': DB[0].APP_NAME,
'size': DB[0].SIZE,
'md5': DB[0].MD5,
'sha1': DB[0].SHA1,
'sha256': DB[0].SHA256,
'packagename': DB[0].PACKAGENAME,
'mainactivity': DB[0].MAINACTIVITY,
'targetsdk': DB[0].TARGET_SDK,
'maxsdk': DB[0].MAX_SDK,
'minsdk': DB[0].MIN_SDK,
'androvername': DB[0].ANDROVERNAME,
'androver': DB[0].ANDROVER,
'manifest': DB[0].MANIFEST_ANAL,
'permissions': DB[0].PERMISSIONS,
'files': python_list(DB[0].FILES),
'certz': DB[0].CERTZ,
'activities': python_list(DB[0].ACTIVITIES),
'receivers': python_list(DB[0].RECEIVERS),
'providers': python_list(DB[0].PROVIDERS),
'services': python_list(DB[0].SERVICES),
'libraries': python_list(DB[0].LIBRARIES),
'act_count': DB[0].CNT_ACT,
'prov_count': DB[0].CNT_PRO,
'serv_count': DB[0].CNT_SER,
'bro_count': DB[0].CNT_BRO,
'certinfo': DB[0].CERT_INFO,
'issued': DB[0].ISSUED,
'native': DB[0].NATIVE,
'dynamic': DB[0].DYNAMIC,
'reflection': DB[0].REFLECT,
'crypto': DB[0].CRYPTO,
'obfus': DB[0].OBFUS,
'api': DB[0].API,
'dang': DB[0].DANG,
'urls': DB[0].URLS,
'domains': python_dict(DB[0].DOMAINS),
'emails': DB[0].EMAILS,
'strings': python_list(DB[0].STRINGS),
'zipped': DB[0].ZIPPED,
'mani': DB[0].MANI
}
if TYP == 'APK':
template = get_template("static_analysis_pdf.html")
else:
template = get_template("static_analysis_zip_pdf.html")
else:
return HttpResponse(json.dumps({"report": "Report not Found"}),
content_type="application/json; charset=utf-8")
elif re.findall('IPA|IOSZIP', TYP):
if TYP == 'IPA':
DB = StaticAnalyzerIPA.objects.filter(MD5=MD5)
if DB.exists():
print "\n[INFO] Fetching data from DB for PDF Report Generation (IOS IPA)"
context = {
'title': DB[0].TITLE,
'name': DB[0].APPNAMEX,
'size': DB[0].SIZE,
'md5': DB[0].MD5,
'sha1': DB[0].SHA1,
'sha256': DB[0].SHA256,
'plist': DB[0].INFOPLIST,
'bin_name': DB[0].BINNAME,
'id': DB[0].IDF,
'ver': DB[0].VERSION,
'sdk': DB[0].SDK,
'pltfm': DB[0].PLTFM,
'min': DB[0].MINX,
'bin_anal': DB[0].BIN_ANAL,
'libs': DB[0].LIBS,
'files': python_list(DB[0].FILES),
'file_analysis': DB[0].SFILESX,
'strings': DB[0].STRINGS
}
template = get_template("ios_binary_analysis_pdf.html")
else:
return HttpResponse(json.dumps({"report": "Report not Found"}),
content_type="application/json; charset=utf-8")
elif TYP == 'IOSZIP':
DB = StaticAnalyzerIOSZIP.objects.filter(MD5=MD5)
if DB.exists():
print "\n[INFO] Fetching data from DB for PDF Report Generation (IOS ZIP)"
context = {
'title': DB[0].TITLE,
'name': DB[0].APPNAMEX,
'size': DB[0].SIZE,
'md5': DB[0].MD5,
'sha1': DB[0].SHA1,
'sha256': DB[0].SHA256,
'plist': DB[0].INFOPLIST,
'bin_name': DB[0].BINNAME,
'id': DB[0].IDF,
'ver': DB[0].VERSION,
'sdk': DB[0].SDK,
'pltfm': DB[0].PLTFM,
'min': DB[0].MINX,
'bin_anal': DB[0].BIN_ANAL,
'libs': DB[0].LIBS,
'files': python_list(DB[0].FILES),
'file_analysis': DB[0].SFILESX,
'api': DB[0].HTML,
'insecure': DB[0].CODEANAL,
'urls': DB[0].URLnFile,
'domains': python_dict(DB[0].DOMAINS),
'emails': DB[0].EmailnFile
}
template = get_template("ios_source_analysis_pdf.html")
else:
return HttpResponse(json.dumps({"report": "Report not Found"}),
content_type="application/json; charset=utf-8")
elif re.findall('APPX',TYP):
if TYP == 'APPX':
db_entry = StaticAnalyzerWindows.objects.filter( # pylint: disable-msg=E1101
MD5=MD5
)
if db_entry.exists():
print "\n[INFO] Fetching data from DB for PDF Report Generation (APPX)"
context = {
'title' : db_entry[0].TITLE,
'name' : db_entry[0].APP_NAME,
'pub_name' : db_entry[0].PUB_NAME,
'size' : db_entry[0].SIZE,
'md5': db_entry[0].MD5,
'sha1' : db_entry[0].SHA1,
'sha256' : db_entry[0].SHA256,
'bin_name' : db_entry[0].BINNAME,
'version' : db_entry[0].VERSION,
'arch' : db_entry[0].ARCH,
'compiler_version' : db_entry[0].COMPILER_VERSION,
'visual_studio_version' : db_entry[0].VISUAL_STUDIO_VERSION,
'visual_studio_edition' : db_entry[0].VISUAL_STUDIO_EDITION,
'target_os' : db_entry[0].TARGET_OS,
'appx_dll_version' : db_entry[0].APPX_DLL_VERSION,
'proj_guid' : db_entry[0].PROJ_GUID,
'opti_tool' : db_entry[0].OPTI_TOOL,
'target_run' : db_entry[0].TARGET_RUN,
'files' : python_list(db_entry[0].FILES),
'strings' : db_entry[0].STRINGS,
'bin_an_results' : python_list(db_entry[0].BIN_AN_RESULTS),
'bin_an_warnings' : python_list(db_entry[0].BIN_AN_WARNINGS)
}
template= get_template("windows_binary_analysis_pdf.html")
else:
return HttpResponse(json.dumps({"type": "Type is not Allowed"}),
content_type="application/json; charset=utf-8")
html = template.render(context)
result = StringIO()
pdf = pisa.pisaDocuement(StringIO("{0}".format(
html.encode('utf-8'))), result, encoding='utf-8')
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
else:
return HttpResponseRedirect('/error/')
else:
return HttpResponse(json.dumps({"md5": "Invalid MD5"}),
content_type="application/json; charset=utf-8")
except:
PrintException("[ERROR] PDF Report Generation Error")
return HttpResponseRedirect('/error/')
0
Example 73
@transaction.atomic
def handle_request(request, more_id=None):
validators = {
reverse('lrs:statements').lower(): {
"POST": req_validate.statements_post,
"GET": req_validate.statements_get,
"PUT": req_validate.statements_put,
"HEAD": req_validate.statements_get
},
reverse('lrs:statements_more_placeholder').lower(): {
"GET": req_validate.statements_more_get,
"HEAD": req_validate.statements_more_get
},
reverse('lrs:activity_state').lower(): {
"POST": req_validate.activity_state_post,
"PUT": req_validate.activity_state_put,
"GET": req_validate.activity_state_get,
"HEAD": req_validate.activity_state_get,
"DELETE": req_validate.activity_state_delete
},
reverse('lrs:activity_profile').lower(): {
"POST": req_validate.activity_profile_post,
"PUT": req_validate.activity_profile_put,
"GET": req_validate.activity_profile_get,
"HEAD": req_validate.activity_profile_get,
"DELETE": req_validate.activity_profile_delete
},
reverse('lrs:activities').lower(): {
"GET": req_validate.activities_get,
"HEAD": req_validate.activities_get
},
reverse('lrs:agent_profile').lower(): {
"POST": req_validate.agent_profile_post,
"PUT": req_validate.agent_profile_put,
"GET": req_validate.agent_profile_get,
"HEAD": req_validate.agent_profile_get,
"DELETE": req_validate.agent_profile_delete
},
reverse('lrs:agents').lower(): {
"GET": req_validate.agents_get,
"HEAD": req_validate.agents_get
}
}
processors = {
reverse('lrs:statements').lower(): {
"POST": req_process.statements_post,
"GET": req_process.statements_get,
"HEAD": req_process.statements_get,
"PUT": req_process.statements_put
},
reverse('lrs:statements_more_placeholder').lower(): {
"GET": req_process.statements_more_get,
"HEAD": req_process.statements_more_get
},
reverse('lrs:activity_state').lower(): {
"POST": req_process.activity_state_post,
"PUT": req_process.activity_state_put,
"GET": req_process.activity_state_get,
"HEAD": req_process.activity_state_get,
"DELETE": req_process.activity_state_delete
},
reverse('lrs:activity_profile').lower(): {
"POST": req_process.activity_profile_post,
"PUT": req_process.activity_profile_put,
"GET": req_process.activity_profile_get,
"HEAD": req_process.activity_profile_get,
"DELETE": req_process.activity_profile_delete
},
reverse('lrs:activities').lower(): {
"GET": req_process.activities_get,
"HEAD": req_process.activities_get
},
reverse('lrs:agent_profile').lower(): {
"POST": req_process.agent_profile_post,
"PUT": req_process.agent_profile_put,
"GET": req_process.agent_profile_get,
"HEAD": req_process.agent_profile_get,
"DELETE": req_process.agent_profile_delete
},
reverse('lrs:agents').lower(): {
"GET": req_process.agents_get,
"HEAD": req_process.agents_get
}
}
try:
r_dict = req_parse.parse(request, more_id)
path = request.path.lower()
if path.endswith('/'):
path = path.rstrip('/')
# Cutoff more_id
if 'more' in path:
path = "%s/%s" % (reverse('lrs:statements').lower(), "more")
req_dict = validators[path][r_dict['method']](r_dict)
return processors[path][req_dict['method']](req_dict)
except (BadRequest, OauthBadRequest, HttpResponseBadRequest) as err:
log_exception(request.path, err)
response = HttpResponse(err.message, status=400)
except (Unauthorized, OauthUnauthorized) as autherr:
log_exception(request.path, autherr)
response = HttpResponse(autherr, status=401)
response['WWW-Authenticate'] = 'Basic realm="ADLLRS"'
except Forbidden as forb:
log_exception(request.path, forb)
response = HttpResponse(forb.message, status=403)
except NotFound as nf:
log_exception(request.path, nf)
response = HttpResponse(nf.message, status=404)
except Conflict as c:
log_exception(request.path, c)
response = HttpResponse(c.message, status=409)
except PreconditionFail as pf:
log_exception(request.path, pf)
response = HttpResponse(pf.message, status=412)
except Exception as err:
log_exception(request.path, err)
response = HttpResponse(err.message, status=500)
return response
0
Example 74
Project: AuShadha Source File: views.py
@login_required
def visit(request, patient_id=None):
if request.method == "GET" and request.is_ajax():
if patient_id:
patient_id = int(patient_id)
else:
try:
patient_id = int(request.GET.get('patient_id'))
pat_obj = PatientDetail.objects.get(pk=patient_id)
pat_urls = pat_obj.urls
visit_obj = VisitDetail.objects.filter(
patient_detail=pat_obj)
prev_visit_obj = VisitDetail.objects.filter(
patient_detail=pat_obj).filter(is_active=False)
active_visit_obj = VisitDetail.objects.filter(
patient_detail=pat_obj).filter(is_active=True)
except(AttributeError, NameError, KeyError, TypeError, ValueError):
raise Http404("ERROR! Bad Request Parameters")
except(AttributeError, NameError, KeyError, TypeError, ValueError):
raise Http404("ERROR! Requested Patient Data Does not exist")
#pat_obj.generate_urls()
#adm_obj = AdmissionDetail.objects.filter(
#patient_detail=pat_obj)
#demographics_obj = Demographics.objects.filter(
#patient_detail=pat_obj)
#social_history_obj = SocialHistory.objects.filter(
#patient_detail=pat_obj)
#family_history_obj = FamilyHistory.objects.filter(
#patient_detail=pat_obj)
#medical_history_obj = MedicalHistory.objects.filter(
#patient_detail=pat_obj)
#surgical_history_obj = SurgicalHistory.objects.filter(
#patient_detail=pat_obj)
#medication_list_obj = MedicationList.objects.filter(
#patient_detail=pat_obj)
#allergy_obj = Allergy.objects.filter(
#patient_detail=pat_obj)
#pat_inv_obj = VisitInv.objects.filter(
#visit_detail__patient_detail=pat_obj)
#pat_imaging_obj = VisitImaging.objects.filter(
#visit_detail__patient_detail=pat_obj)
tree = DijitTree()
if pat_obj.can_add_new_visit(pat_obj):
new_visit = DijitTreeNode({"name": "New OPD Visit",
"type": "application",
"id": "NEW_OPD_VISIT",
"addUrl": pat_urls['add']['visit']
})
tree.add_child_node(new_visit)
if active_visit_obj:
active_visits = VisitDetail.objects.filter(
patient_detail=pat_obj).filter(is_active=True)
active_visits_node = DijitTreeNode( {"name": "Active Visits",
"type": "application",
"id": "ACTIVE_VISITS",
"addUrl": None,
'editUrl': None,
'delUrl': None
})
tree.add_child_node(active_visits_node)
for active_visit in active_visits:
av_urls = active_visit.urls
av = DijitTreeNode({"name": active_visit.visit_date.date().isoformat(),
"type": "active_visit",
"id": "ACTIVE_VISITS_" + str(active_visit.id),
"addUrl": None,
'editUrl': av_urls['edit'],
'delUrl': av_urls['del']
})
av_fu = DijitTreeNode({"name": "Add Follow-Up",
"type": "visit_follow_up_add",
"id": "VISIT_FOLLOW_UP_ADD_" + str(active_visit.id),
"addUrl": av_urls['add']['follow_up'],
})
av.add_child_node(av_fu)
av_orders = DijitTreeNode({"name": "Orders",
"type": "application",
"id": "ACTIVE_VISIT_" + str(active_visit.id) + "_ORDERS_AND_PRESCRIPTION",
"addUrl": None,
})
av.add_child_node(av_orders)
av_close = DijitTreeNode({"name": "Close",
"type": "close_visit",
"id": "VISIT_CLOSE_" + str(active_visit.id),
"addUrl": active_visit.get_visit_detail_close_url(),
})
av.add_child_node(av_close)
active_visits_node.add_child_node(av)
tree.add_child_node(active_visits_node)
#av_edit = DijitTreeNode({"name" : "Edit" ,
#"type" : "visit",
#"id" : "ACTIVE_VISIT_" + str(active_visit.id) ,
#"addUrl" : None,
#"editUrl" : av_urls['edit'],
#"deUrl" : av_urls['del']
#})
#av_diagnosis = DijitTreeNode({"name" : "Diagnosis" ,
#"type":"application",
#"id":"DIAG" ,
#"addUrl": None,
#})
#av_advice = DijiTreeNode({"name" : "Advice" ,
#"type":"advice",
#"id":"ADVICE" ,
#"addUrl": None,
#})
#av_procedure = DijitTreeNode({"name" : "Procedure" ,
#"type":"procedure",
#"id":"PROC" ,
#"addUrl": None,
#})
#av_calendar = DijiTreeNode({"name" : "Calendar" ,
#"type":"application",
#"id":"CAL" ,
#"addUrl": None,
#})
if active_visit.has_fu_visits():
fu_base = DijitTreeNode({"name": "Follow-ups",
"type": "fu_visits",
"id": "",
"addUrl": None,
"absoluteUrl": None
})
fu_visit = active_visit.has_fu_visits()
for fu in fu_visit:
fu_node = DijitTreeNode({ "name": fu.visit_date.date().isoformat(),
"type": "fu_visit",
"id": "FU_VISIT_" + str(fu.id),
"editUrl": fu.urls['edit'],
"delUrl": fu.urls['del']
})
fu_orders = DijitTreeNode({"name": "Orders",
"type": "application",
"id": "FU_VISIT_" + str(fu.id) + "_ORDERS_AND_PRESCRIPTION",
"addUrl": None,
})
if prev_visit_obj:
base_dict = {"name": "Closed Visits", "type":
"application", "id": "CLOSED_VISITS", 'children': []}
sub_dict = {
"name": "", "type": "visit", "id": "", "editUrl": "", "delUrl": ""}
for visit in prev_visit_obj:
#visit.generate_urls()
v_urls = visit.urls
prev_v = DijitTreeNode({'name': visit.visit_date.date().isoformat() + "(" + visit.op_surgeon.__unicode__() + ")",
'id': "CLOSED_VISIT_" + unicode(visit.id),
'absoluteUrl':visit.get_absolute_url(),
'editUrl':v_urls['edit'],
'delUrl': v_urls['del']})
prev_v_orders = DijitTreeNode({"name": "Orders",
"type": "application",
"id": "CLOSED_VISIT_" + str(visit.id) + "_ORDERS_AND_PRESCRIPTION",
"len": 1,
"addUrl": None,
})
if visit.has_fu_visits():
fu_visit = visit.has_fu_visits()
prev_v_fu_base = DijitTreeNode({"name": "Follow-ups",
"type": "fu_visits",
"id": "CLOSED_FOLLOW_UP_VISITS_" + str(visit.id),
"addUrl": None,
"absoluteUrl": None
})
for fu in fu_visit:
prev_v_fu = DijitTreeNode({"name": fu.visit_date.date().isoformat(),
"type": "fu_visit",
"id": "CLOSED_FU_VISIT_" + str(fu.id),
"editUrl": fu.urls['edit'],
"delUrl": fu.urls['del'],
})
prev_v_orders = DijitTreeNode({"name": "Orders",
"type": "application",
"id": "CLOSED_FU_VISIT_" + str(fu.id) + "_ORDERS_AND_PRESCRIPTION",
"addUrl": None,
})
procedure = DijitTreeNode({"name": "Procedures",
"type": "application",
"id": "PROC",
"addUrl": None,
})
history = DijitTreeNode({"name": "History",
"type": "application",
"id": "HISTORY",
"addUrl": None,
})
medication = DijitTreeNode({"name": "Medication",
"type": "application",
"id": "MEDICATION_LIST",
"addUrl": None,
})
investigation = DijitTreeNode({"name": "Investigation",
"type": "application",
"id": "INV",
"addUrl": None,
})
imaging = DijitTreeNode({"name": "Imaging",
"type": "application",
"id": "IMAG",
"addUrl": None,
})
media = DijitTreeNode({"name" : "Media" ,
"type":"application",
"id":"MEDIA" ,
"addUrl": None
})
docuements = DijitTreeNode({"name" : "Docuements" ,
"type":"patient_docuements_module",
"id":"DOCS" ,
"addUrl": None,
})
media.add_child_node(docuements)
images = DijitTreeNode({"name" : "Images" ,
"type":"patient_images_module",
"id":"IMAGES" ,
"addUrl": None,
})
media.add_child_node(images)
jsondata = tree.to_json()
return HttpResponse(jsondata, content_type="application/json")
0
Example 75
Project: django-compositepks Source File: i18n.py
def javascript_catalog(request, domain='djangojs', packages=None):
"""
Returns the selected language catalog as a javascript library.
Receives the list of packages to check for translations in the
packages parameter either from an infodict or as a +-delimited
string from the request. Default is 'django.conf'.
Additionally you can override the gettext domain for this view,
but usually you don't want to do that, as JavaScript messages
go to the djangojs domain. But this might be needed if you
deliver your JavaScript source from Django templates.
"""
if request.GET:
if 'language' in request.GET:
if check_for_language(request.GET['language']):
activate(request.GET['language'])
if packages is None:
packages = ['django.conf']
if type(packages) in (str, unicode):
packages = packages.split('+')
packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
default_locale = to_locale(settings.LANGUAGE_CODE)
locale = to_locale(get_language())
t = {}
paths = []
# first load all english languages files for defaults
for package in packages:
p = __import__(package, {}, {}, [''])
path = os.path.join(os.path.dirname(p.__file__), 'locale')
paths.append(path)
try:
catalog = gettext_module.translation(domain, path, ['en'])
t.update(catalog._catalog)
except IOError:
# 'en' catalog was missing. This is harmless.
pass
# next load the settings.LANGUAGE_CODE translations if it isn't english
if default_locale != 'en':
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [default_locale])
except IOError:
catalog = None
if catalog is not None:
t.update(catalog._catalog)
# last load the currently selected language, if it isn't identical to the default.
if locale != default_locale:
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [locale])
except IOError:
catalog = None
if catalog is not None:
t.update(catalog._catalog)
src = [LibHead]
plural = None
if '' in t:
for l in t[''].split('\n'):
if l.startswith('Plural-Forms:'):
plural = l.split(':',1)[1].strip()
if plural is not None:
# this should actually be a compiled function of a typical plural-form:
# Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=',1)[1]
src.append(PluralIdx % plural)
else:
src.append(SimplePlural)
csrc = []
pdict = {}
for k, v in t.items():
if k == '':
continue
if type(k) in (str, unicode):
csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
elif type(k) == tuple:
if k[0] not in pdict:
pdict[k[0]] = k[1]
else:
pdict[k[0]] = max(k[1], pdict[k[0]])
csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
else:
raise TypeError, k
csrc.sort()
for k,v in pdict.items():
src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1))))
src.extend(csrc)
src.append(LibFoot)
src.append(InterPolate)
src = ''.join(src)
return http.HttpResponse(src, 'text/javascript')
0
Example 76
Project: edx-platform Source File: views.py
@cache_control(must_revalidate=True, max_age=settings.FOOTER_BROWSER_CACHE_MAX_AGE)
def footer(request):
"""Retrieve the branded footer.
This end-point provides information about the site footer,
allowing for consistent display of the footer across other sites
(for example, on the marketing site and blog).
It can be used in one of two ways:
1) A client renders the footer from a JSON description.
2) A browser loads an HTML representation of the footer
and injects it into the DOM. The HTML includes
CSS and JavaScript links.
In case (2), we assume that the following dependencies
are included on the page:
a) JQuery (same version as used in edx-platform)
b) font-awesome (same version as used in edx-platform)
c) Open Sans web fonts
Example: Retrieving the footer as JSON
GET /api/branding/v1/footer
Accepts: application/json
{
"navigation_links": [
{
"url": "http://example.com/about",
"name": "about",
"title": "About"
},
# ...
],
"social_links": [
{
"url": "http://example.com/social",
"name": "facebook",
"icon-class": "fa-facebook-square",
"title": "Facebook",
"action": "Sign up on Facebook!"
},
# ...
],
"mobile_links": [
{
"url": "http://example.com/android",
"name": "google",
"image": "http://example.com/google.png",
"title": "Google"
},
# ...
],
"legal_links": [
{
"url": "http://example.com/terms-of-service.html",
"name": "terms_of_service",
"title': "Terms of Service"
},
# ...
],
"openedx_link": {
"url": "http://open.edx.org",
"title": "Powered by Open edX",
"image": "http://example.com/openedx.png"
},
"logo_image": "http://example.com/static/images/logo.png",
"copyright": "EdX, Open edX, and the edX and Open edX logos are \
registered trademarks or trademarks of edX Inc."
}
Example: Retrieving the footer as HTML
GET /api/branding/v1/footer
Accepts: text/html
Example: Including the footer with the "Powered by OpenEdX" logo
GET /api/branding/v1/footer?show-openedx-logo=1
Accepts: text/html
Example: Retrieving the footer in a particular language
GET /api/branding/v1/footer?language=en
Accepts: text/html
Example: Retrieving the footer with all JS and CSS dependencies (for testing)
GET /api/branding/v1/footer?include-dependencies=1
Accepts: text/html
"""
if not branding_api.is_enabled():
raise Http404
# Use the content type to decide what representation to serve
accepts = request.META.get('HTTP_ACCEPT', '*/*')
# Show the OpenEdX logo in the footer
show_openedx_logo = bool(request.GET.get('show-openedx-logo', False))
# Include JS and CSS dependencies
# This is useful for testing the end-point directly.
include_dependencies = bool(request.GET.get('include-dependencies', False))
# Override the language if necessary
language = request.GET.get('language', translation.get_language())
# Render the footer information based on the extension
if 'text/html' in accepts or '*/*' in accepts:
cache_key = u"branding.footer.{params}.html".format(
params=urllib.urlencode({
'language': language,
'show_openedx_logo': show_openedx_logo,
'include_dependencies': include_dependencies,
})
)
content = cache.get(cache_key)
if content is None:
with translation.override(language):
content = _render_footer_html(request, show_openedx_logo, include_dependencies)
cache.set(cache_key, content, settings.FOOTER_CACHE_TIMEOUT)
return HttpResponse(content, status=200, content_type="text/html; charset=utf-8")
elif 'application/json' in accepts:
cache_key = u"branding.footer.{params}.json".format(
params=urllib.urlencode({
'language': language,
'is_secure': request.is_secure(),
})
)
footer_dict = cache.get(cache_key)
if footer_dict is None:
with translation.override(language):
footer_dict = branding_api.get_footer(is_secure=request.is_secure())
cache.set(cache_key, footer_dict, settings.FOOTER_CACHE_TIMEOUT)
return JsonResponse(footer_dict, 200, content_type="application/json; charset=utf-8")
else:
return HttpResponse(status=406)
0
Example 77
Project: AuShadha Source File: views.py
@login_required
def social_history_edit(request, social_history_id = None):
if request.user:
user = request.user
try:
if social_history_id:
social_history_id = int(social_history_id)
else:
social_history_id = int(request.GET.get('social_history_id'))
social_history_obj = SocialHistory.objects.get(pk=social_history_id)
patient_detail_obj = social_history_obj.patient_detail
if not getattr(patient_detail_obj, 'urls',None):
patient_detail_obj.save()
if not getattr(social_history_obj,'urls',None):
social_history_obj.save()
urls = social_history_obj.urls
else:
urls = social_history_obj.urls
except ValueError or AttributeError or TypeError:
raise Http404("BadRequest: Server Error")
except SocialHistory.DoesNotExist:
raise Http404("BadRequest: Requested Patient SocialHistory Data DoesNotExist")
if request.method == "GET" and request.is_ajax():
social_history_form = SocialHistoryForm(instance=social_history_obj)
patient_detail_obj = social_history_obj.patient_detail
addData = {
"marital_status": social_history_obj.marital_status,
"marital_status_notes": social_history_obj.marital_status_notes,
"occupation": social_history_obj.occupation,
"occupation_notes": social_history_obj.occupation_notes,
"exercise": social_history_obj.exercise,
"exercise_notes": social_history_obj.exercise_notes,
"diet": social_history_obj.diet,
"diet_notes": social_history_obj.diet_notes,
"home_occupants": social_history_obj.home_occupants,
"home_occupants_notes": social_history_obj.home_occupants_notes,
"pets": social_history_obj.pets,
"pets_notes": social_history_obj.pets_notes,
"alcohol": social_history_obj.alcohol,
"alcohol_no": social_history_obj.alcohol_no,
"alcohol_notes": social_history_obj.alcohol_notes,
"tobacco": social_history_obj.tobacco,
"tobacco_no": social_history_obj.tobacco_no,
"tobacco_notes": social_history_obj.tobacco_notes,
"drug_abuse": social_history_obj.drug_abuse,
"drug_abuse_notes": social_history_obj.drug_abuse_notes,
"sexual_preference": social_history_obj.sexual_preference,
"sexual_preference_notes": social_history_obj.sexual_preference_notes,
"current_events": social_history_obj.current_events
}
variable = RequestContext(request,
{"user": user,
"patient_detail_obj": patient_detail_obj,
"social_history_form": social_history_form,
"social_history_obj": social_history_obj,
"addData": addData,
'action': urls['edit'],
'button_label': "Edit",
'canDel': True,
'addUrl': None,
'editUrl': urls['edit'],
'delUrl': urls['del'],
})
return render_to_response('social_history/add_or_edit_form.html', variable)
elif request.method == 'POST' and request.is_ajax():
copy_post = request.POST.copy()
copy_post['home_occupants'] = ",".join(copy_post.getlist('home_occupants'))
copy_post['pets'] = ",".join(copy_post.getlist('pets'))
social_history_form = SocialHistoryForm(copy_post, instance=social_history_obj)
patient_detail_obj = social_history_obj.patient_detail
if social_history_form.is_valid():
social_history_obj = social_history_form.save()
success = True
error_message = "SocialHistory Data Edited Successfully"
form_errors = ''
addData = {
"marital_status": social_history_obj.marital_status,
"marital_status_notes": social_history_obj.marital_status_notes,
"occupation": social_history_obj.occupation,
"occupation_notes": social_history_obj.occupation_notes,
"exercise": social_history_obj.exercise,
"exercise_notes": social_history_obj.exercise_notes,
"diet": social_history_obj.diet_notes,
"home_occupants": social_history_obj.home_occupants,
"home_occupants_notes": social_history_obj.home_occupants_notes,
"pets": social_history_obj.pets,
"pets_notes": social_history_obj.pets_notes,
"alcohol": social_history_obj.alcohol,
"alcohol_no": social_history_obj.alcohol_no,
"alcohol_notes": social_history_obj.alcohol_notes,
"tobacco": social_history_obj.tobacco,
"tobacco_no": social_history_obj.tobacco_no,
"tobacco_notes": social_history_obj.tobacco_notes,
"drug_abuse": social_history_obj.drug_abuse,
"drug_abuse_notes": social_history_obj.drug_abuse_notes,
"sexual_preference": social_history_obj.sexual_preference,
"sexual_preference_notes": social_history_obj.sexual_preference_notes,
"current_events": social_history_obj.current_events
}
data = {'success': success,
'error_message': error_message,
'form_errors': form_errors,
"addData": addData
}
else:
data = {'success': False,
'error_message': aumodelformerrorformatter_factory(social_history_form),
'form_errors':error_message,
'addData':None
}
jsondata = json.dumps(data)
return HttpResponse(jsondata, content_type='application/json')
else:
raise Http404("BadRequest: Unsupported Request Method")
0
Example 78
Project: django-lfs Source File: variants.py
@permission_required("core.manage_shop")
def update_variants(request, product_id):
"""Updates/Deletes variants with passed ids (via request body) dependent on
given action (also via request body).
"""
product = lfs_get_object_or_404(Product, pk=product_id)
message = ''
action = request.POST.get("action")
if action == "delete":
message = _(u"Variants have been deleted.")
for key in request.POST.keys():
if key.startswith("delete-"):
try:
prop_id = key.split("-")[1]
variant = Product.objects.get(pk=prop_id)
except (IndexError, ObjectDoesNotExist):
continue
else:
if product.default_variant == variant:
product.default_variant = None
product.save()
variant.delete()
elif action == "update":
# TODO: change all of these to formsets or something that will allow for error hangling/messages
message = _(u"Variants have been saved.")
for key, value in request.POST.items():
if key.startswith("variant-"):
prop_id = key.split("-")[1]
try:
variant = Product.objects.get(pk=prop_id)
except ObjectDoesNotExist:
continue
else:
for name in ("sku", "price"):
value = request.POST.get("%s-%s" % (name, prop_id))
if value != "":
if name == 'price':
value = float(value)
setattr(variant, name, value)
# handle slug - ensure it is unique
slug = request.POST.get("slug-%s" % prop_id)
if variant.slug != slug:
counter = 1
new_slug = slug[:80]
while Product.objects.exclude(pk=variant.pk).filter(slug=new_slug).exists():
new_slug = '%s-%s' % (slug[:(79 - len(str(counter)))], counter)
counter += 1
variant.slug = new_slug
# name
variant.name = request.POST.get("name-%s" % prop_id)
# active
active = request.POST.get("active-%s" % prop_id)
if active:
variant.active = True
else:
variant.active = False
# active attributes
for name in ("active_price", "active_sku", "active_name"):
value = request.POST.get("%s-%s" % (name, prop_id))
if value:
setattr(variant, name, True)
else:
setattr(variant, name, False)
# position
position = request.POST.get("position-%s" % prop_id)
try:
variant.variant_position = int(position)
except ValueError:
variant.variant_position = 10
# default variant
try:
product.default_variant_id = int(request.POST.get("default_variant"))
except TypeError:
pass
else:
product.save()
variant.save()
elif key.startswith("property"):
# properties are marshalled as: property-variant_id|property_group_id|property_id
temp = key.split("-")[1]
variant_id, property_group_id, property_id = temp.split("|")
if property_group_id == '0': # local properties are not bound to property groups
property_group_id = None
try:
variant = Product.objects.get(pk=variant_id)
except Product.DoesNotExist:
continue
prop = Property.objects.get(pk=property_id)
ppv = None
try:
ppv = ProductPropertyValue.objects.get(product=variant,
property_id=property_id,
property_group_id=property_group_id,
type=PROPERTY_VALUE_TYPE_VARIANT)
except ProductPropertyValue.DoesNotExist:
pass
if prop.filterable: # it is possible that multiple values are selected for filter
ppv_filterables = ProductPropertyValue.objects.filter(product=variant,
property_group_id=property_group_id,
property_id=property_id,
type=PROPERTY_VALUE_TYPE_FILTER)
if value != '':
is_changed = True
if not ppv:
ppv = ProductPropertyValue.objects.create(product=variant,
property_group_id=property_group_id,
property_id=property_id,
type=PROPERTY_VALUE_TYPE_VARIANT,
value=value)
else:
is_changed = ppv.value != value
ppv.value = value
ppv.save()
if prop.filterable and is_changed:
ppv_filterables.delete()
ProductPropertyValue.objects.create(product=variant,
property_group_id=property_group_id,
property_id=property_id,
value=value,
type=PROPERTY_VALUE_TYPE_FILTER)
elif ppv:
ppv.delete()
ppv_filterables.delete()
# Refresh variant positions
for i, variant in enumerate(product.variants.order_by("variant_position")):
variant.variant_position = (i + 1) * 10
variant.save()
# Send a signal to update cache
product_changed.send(product)
pid = product.get_parent().pk
invalidate_cache_group_id('properties-%s' % pid)
html = (
("#variants", manage_variants(request, product_id, as_string=True)),
("#selectable-products-inline", _selectable_products_inline(request, product)),
)
result = json.dumps({
"html": html,
"message": message,
}, cls=LazyEncoder)
return HttpResponse(result, content_type='application/json')
0
Example 79
Project: edx-platform Source File: middleware.py
def process_request(self, request):
"""Process the given request"""
asset_path = request.path
if self.is_asset_request(request):
# Make sure we can convert this request into a location.
if AssetLocator.CANONICAL_NAMESPACE in asset_path:
asset_path = asset_path.replace('block/', 'block@', 1)
# If this is a versioned request, pull out the digest and chop off the prefix.
requested_digest = None
if StaticContent.is_versioned_asset_path(asset_path):
requested_digest, asset_path = StaticContent.parse_versioned_asset_path(asset_path)
# Make sure we have a valid location value for this asset.
try:
loc = StaticContent.get_location_from_path(asset_path)
except (InvalidLocationError, InvalidKeyError):
return HttpResponseBadRequest()
# Attempt to load the asset to make sure it exists, and grab the asset digest
# if we're able to load it.
actual_digest = None
try:
content = self.load_asset_from_location(loc)
actual_digest = getattr(content, "content_digest", None)
except (ItemNotFoundError, NotFoundError):
return HttpResponseNotFound()
# If this was a versioned asset, and the digest doesn't match, redirect
# them to the actual version.
if requested_digest is not None and actual_digest is not None and (actual_digest != requested_digest):
actual_asset_path = StaticContent.add_version_to_asset_path(asset_path, actual_digest)
return HttpResponsePermanentRedirect(actual_asset_path)
# Set the basics for this request. Make sure that the course key for this
# asset has a run, which old-style courses do not. Otherwise, this will
# explode when the key is serialized to be sent to NR.
safe_course_key = loc.course_key
if safe_course_key.run is None:
safe_course_key = safe_course_key.replace(run='only')
newrelic.agent.add_custom_parameter('course_id', safe_course_key)
newrelic.agent.add_custom_parameter('org', loc.org)
newrelic.agent.add_custom_parameter('contentserver.path', loc.path)
# Figure out if this is a CDN using us as the origin.
is_from_cdn = StaticContentServer.is_cdn_request(request)
newrelic.agent.add_custom_parameter('contentserver.from_cdn', is_from_cdn)
# Check if this content is locked or not.
locked = self.is_content_locked(content)
newrelic.agent.add_custom_parameter('contentserver.locked', locked)
# Check that user has access to the content.
if not self.is_user_authorized(request, content, loc):
return HttpResponseForbidden('Unauthorized')
# Figure out if the client sent us a conditional request, and let them know
# if this asset has changed since then.
last_modified_at_str = content.last_modified_at.strftime(HTTP_DATE_FORMAT)
if 'HTTP_IF_MODIFIED_SINCE' in request.META:
if_modified_since = request.META['HTTP_IF_MODIFIED_SINCE']
if if_modified_since == last_modified_at_str:
return HttpResponseNotModified()
# *** File streaming within a byte range ***
# If a Range is provided, parse Range attribute of the request
# Add Content-Range in the response if Range is structurally correct
# Request -> Range attribute structure: "Range: bytes=first-[last]"
# Response -> Content-Range attribute structure: "Content-Range: bytes first-last/totalLength"
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
response = None
if request.META.get('HTTP_RANGE'):
# If we have a StaticContent, get a StaticContentStream. Can't manipulate the bytes otherwise.
if isinstance(content, StaticContent):
content = AssetManager.find(loc, as_stream=True)
header_value = request.META['HTTP_RANGE']
try:
unit, ranges = parse_range_header(header_value, content.length)
except ValueError as exception:
# If the header field is syntactically invalid it should be ignored.
log.exception(
u"%s in Range header: %s for content: %s", exception.message, header_value, unicode(loc)
)
else:
if unit != 'bytes':
# Only accept ranges in bytes
log.warning(u"Unknown unit in Range header: %s for content: %s", header_value, unicode(loc))
elif len(ranges) > 1:
# According to Http/1.1 spec content for multiple ranges should be sent as a multipart message.
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16
# But we send back the full content.
log.warning(
u"More than 1 ranges in Range header: %s for content: %s", header_value, unicode(loc)
)
else:
first, last = ranges[0]
if 0 <= first <= last < content.length:
# If the byte range is satisfiable
response = HttpResponse(content.stream_data_in_range(first, last))
response['Content-Range'] = 'bytes {first}-{last}/{length}'.format(
first=first, last=last, length=content.length
)
response['Content-Length'] = str(last - first + 1)
response.status_code = 206 # Partial Content
newrelic.agent.add_custom_parameter('contentserver.ranged', True)
else:
log.warning(
u"Cannot satisfy ranges in Range header: %s for content: %s", header_value, unicode(loc)
)
return HttpResponse(status=416) # Requested Range Not Satisfiable
# If Range header is absent or syntactically invalid return a full content response.
if response is None:
response = HttpResponse(content.stream_data())
response['Content-Length'] = content.length
newrelic.agent.add_custom_parameter('contentserver.content_len', content.length)
newrelic.agent.add_custom_parameter('contentserver.content_type', content.content_type)
# "Accept-Ranges: bytes" tells the user that only "bytes" ranges are allowed
response['Accept-Ranges'] = 'bytes'
response['Content-Type'] = content.content_type
# Set any caching headers, and do any response cleanup needed. Based on how much
# middleware we have in place, there's no easy way to use the built-in Django
# utilities and properly sanitize and modify a response to ensure that it is as
# cacheable as possible, which is why we do it ourselves.
self.set_caching_headers(content, response)
return response
0
Example 80
Project: 1flow Source File: read.py
def read_with_endless_pagination(request, **kwargs):
""" Central view for ALL reading lists. """
(query_kwargs, primary_mode) = \
_rwep_generate_query_kwargs(request, **kwargs)
user = request.user
# —————————————————————————————————————————————————————— Search preparation
search = request.GET.get('search', None)
if request.is_ajax():
# Ajax requests for django-endless-pagination
# infinite scrolling. Get search query if any.
search = request.session.get('search', None)
else:
# Classic access. Update the session for
# django-endless-pagination ajax requests.
search_cleared = search == u'' and request.session['search'] != u''
request.session['search'] = search
if search_cleared:
if request.resolver_match.view_name == u'read_all':
return redirect('source_selector')
return redirect(request.path)
# ———————————————————————————————————————————————————————————— Subscription
# A “feed” (from the user point of view) is actually
# a subscription (from the developer point of view).
subscription = kwargs.get('feed', None)
if subscription:
subscription = Subscription.objects.get(id=subscription)
if subscription.user != user:
if user.has_staff_access:
messages.warning(request,
_(u'As administrator, you are '
u'accessing the feed of another user. '
u'USE WITH CAUTION.'), extra_tags='sticky')
elif user.is_staff_or_superuser_and_enabled:
return HttpResponseForbidden(
u'Staff access explicitely '
u'denied (check config.STAFF_HAS_FULL_ACCESS)')
else:
return HttpResponseForbidden('Not Owner')
query_kwargs[u'subscriptions'] = subscription
# —————————————————————————————————————————————————————————————————— Folder
folder = kwargs.get('folder', None)
if folder:
folder = Folder.objects.get(id=folder)
if folder.user != user:
if user.has_staff_access:
messages.warning(request,
_(u'As administrator, you are '
u'accessing the feed of another user. '
u'USE WITH CAUTION.'), extra_tags='sticky')
elif user.is_staff_or_superuser_and_enabled:
return HttpResponseForbidden(
u'Staff access explicitely denied '
u'(check config.STAFF_HAS_FULL_ACCESS)')
else:
return HttpResponseForbidden('Not Owner')
# LOGGER.info(u'Refining reads by folder %s', folder)
query_kwargs[u'subscriptions__in'] = Subscription.objects.filter(
folders__in=folder.get_descendants(include_self=True))
order_by = _rwep_generate_order_by(request, primary_mode,
subscription, **kwargs)
# —————————————————————————————————————————————————————————————————— Search
if search:
isearch = search.lower()
# Implement these loops for multi-words search.
for term in isearch.split():
if term.startswith(u'+'):
pass
elif term.startswith(u'-'):
pass
if subscription:
user_feeds = [subscription.feed]
elif folder:
user_feeds = [
s.feed for s in Subscription.objects.filter(folders=folder)
]
else:
user_feeds = [s.feed for s in user.subscriptions]
# LOGGER.info(u'Matched user feeds for search “%s”: %s',
# isearch, len(user_feeds))
# NOTE: sync these filters with core.article.is_good
# and core.feed.is_good
matched_articles = BaseItem.objects.filter(
feeds__in=user_feeds,
duplicate_of=None,
).filter(
# Article.translate_polymorphic_Q_object(
Q(Article___url_absolute=True,
Article___content_type__in=CONTENT_TYPES_FINAL)
| Q(instance_of=Article)
# )
)
# LOGGER.info(u'First-pass filtered articles for search “%s”: %s',
# isearch, matched_articles.count())
if config.SEARCH_DB_EXTENDED_FIELDS:
matched_articles = matched_articles.filter(
Q(name__icontains=isearch)
| (
Q(instance_of=Article)
& (
Q(Article___excerpt__icontains=isearch)
| Q(Article___content__icontains=isearch)
)
)
| (
Q(instance_of=Email)
& Q(Email___is_hidden=False)
& Q(Email___content__icontains=isearch)
)
)
else:
matched_articles = matched_articles.filter(
Q(name__icontains=isearch)
)
# LOGGER.info(u'Matched articles for search “%s”: %s',
# isearch, matched_articles.count())
tags = set()
for term in search.split():
try:
tag = Tag.objects.get(name=term)
except:
# Not a tag ?
pass
else:
tags.add(tag)
# ———————————————————————————————————————————————— Search final queries
if tags:
reads = _rwep_wrap_order_by(
user.reads.filter(**query_kwargs).filter(
Q(tags__in=tags) | Q(item__in=matched_articles)
).distinct(), order_by)
else:
reads = _rwep_wrap_order_by(user.reads.filter(
item__in=matched_articles, **query_kwargs).distinct(), order_by)
# ——————————————————————————————————————————————————— NO search final query
else:
reads = _rwep_wrap_order_by(user.reads.filter(**query_kwargs), order_by)
header_text_left, header_text_right = _rwep_build_page_header_text(
subscription, folder, user, primary_mode)
context = {
u'reads': reads,
u'subscription': subscription,
u'folder': folder,
u'current_mode': primary_mode[0],
u'mode_negated': primary_mode[1],
u'search': search,
# 'user' is already there, via a context processor.
u'read_page_header_text_left': header_text_left,
u'read_page_header_text_right': header_text_right,
# are we rendering the first "main"
# page, or just a subset via ajax?
u'initial': False,
}
# ——————————————————————————————————————————————————————————— Ajax requests
if request.is_ajax():
if request.GET.get('count', False):
count = reads.count()
#
# Check and update cache counters
#
if search is None:
try:
_rwep_ajax_update_counters(kwargs,
query_kwargs,
user, count)
except UnicodeDecodeError:
pass
if subscription:
_rwep_special_update_counters(subscription, user)
#
# prepare the "inline mini-template" for ajax update.
#
mode, negated = primary_mode
if mode == 'is_read' and not negated:
mode = 'is_unread'
singular_text, plural_text = READ_STATUS_DATA[mode]['list_headers']
if count == 0:
rendered_text = _(u'no item')
elif count == 1:
rendered_text = singular_text % {'count': count}
else:
rendered_text = plural_text % {'count': count}
return HttpResponse(rendered_text)
elif request.GET.get('mark_all_read', False):
latest_displayed_read = user.reads.get(
item=BaseItem.objects.get(
id=request.GET.get('mark_all_read')))
_rwep_ajax_mark_all_read(subscription, folder, user,
latest_displayed_read)
return HttpResponse('DONE')
else:
template = u'snippets/read/read-endless-page.html'
# Computing tenths_counter here is much efficient than doing:
# {% captureas tenths_counter %}{{ request.GET['page']|mul:10 }}{% endcaptureas %} # NOQA
# in the template…
context[u'tenths_counter'] = \
(get_page_number_from_request(request) - 1) \
* config.READ_INFINITE_ITEMS_PER_FETCH
# LOGGER.info(u'Ajax with %s', context.get('tenths_counter'))
# ———————————————————————————————————————————————————— Standard GET request
else:
template = u'read-endless.html'
context[u'initial'] = True
return render(request, template, context)
0
Example 81
Project: open-context-py Source File: views.py
def subjects_html_view(request, spatial_context=None):
""" returns HTML representation of subjects search
"""
mem_cache_obj = MemoryCache()
mem_cache_obj.ping_redis_server()
csv_downloader = False # provide CSV downloader interface
if request.GET.get('csv') is not None:
csv_downloader = True
chart = False # provide a chart, now only experimental
if request.GET.get('chart') is not None:
chart = True
rp = RootPath()
base_url = rp.get_baseurl()
rd = RequestDict()
request_dict_json = rd.make_request_dict_json(request,
spatial_context)
if rd.security_ok is False:
template = loader.get_template('400.html')
context = RequestContext(request,
{'abusive': True})
return HttpResponse(template.render(context), status=400)
elif rd.do_bot_limit:
cache_control(no_cache=True)
# redirect bot requests away from faceted search where
# they can negatively impact performance
return redirect('/subjects-search/', permanent=False)
else:
# url and json_url neeed for view templating
url = request.get_full_path()
if 'http://' not in url \
and 'https://' not in url:
url = base_url + url
if '?' in url:
json_url = url.replace('?', '.json?')
else:
json_url = url + '.json'
# see if search results are cached. this is not done
# with a view decorator, because we want to handle bots differently
db_cache = DatabaseCache()
cache_key = db_cache.make_cache_key('subjects-search',
request_dict_json)
if rd.refresh_cache:
# the request wanted to refresh the cache
db_cache.remove_cache_object(cache_key)
# get the search result JSON-LD, if it exists in cache
json_ld = db_cache.get_cache_object(cache_key)
if json_ld is None:
# cached result is not found, so make it with a new search
solr_s = SolrSearch()
solr_s.is_bot = rd.is_bot # True if bot detected
solr_s.do_bot_limit = rd.do_bot_limit # Toggle limits on facets for bots
solr_s.mem_cache_obj = mem_cache_obj
solr_s.item_type_limit = 'subjects'
if solr_s.solr is not False:
response = solr_s.search_solr(request_dict_json)
mem_cache_obj = solr_s.mem_cache_obj # reused cached memory items
m_json_ld = MakeJsonLd(request_dict_json)
m_json_ld.base_search_link = '/subjects-search/'
# share entities already looked up. Saves database queries
m_json_ld.mem_cache_obj = mem_cache_obj
m_json_ld.request_full_path = request.get_full_path()
m_json_ld.spatial_context = spatial_context
json_ld = m_json_ld.convert_solr_json(response.raw_content)
mem_cache_obj = m_json_ld.mem_cache_obj
# now cache the resulting JSON-LD
db_cache.save_cache_object(cache_key, json_ld)
if json_ld is not None:
req_neg = RequestNegotiation('text/html')
req_neg.supported_types = ['application/json',
'application/ld+json',
'application/vnd.geo+json']
if 'HTTP_ACCEPT' in request.META:
req_neg.check_request_support(request.META['HTTP_ACCEPT'])
if 'json' in req_neg.use_response_type:
# content negotiation requested JSON or JSON-LD
recon_obj = Reconciliation()
json_ld = recon_obj.process(request.GET,
json_ld)
request.content_type = req_neg.use_response_type
return HttpResponse(json.dumps(json_ld,
ensure_ascii=False, indent=4),
content_type=req_neg.use_response_type + "; charset=utf8")
else:
# now make the JSON-LD into an object suitable for HTML templating
st = SearchTemplate(json_ld)
st.process_json_ld()
template = loader.get_template('search/view.html')
props = []
if 'prop' in request.GET:
props = request.GET.getlist('prop')
if len(props) > 1 or st.total_count <= 25000:
# allow downloads, multiple props selected
# or relatively few records
csv_downloader = True
context = RequestContext(request,
{'st': st,
'csv_downloader': csv_downloader,
'chart': chart,
'item_type': 'subjects',
'base_search_link': m_json_ld.base_search_link,
'url': url,
'json_url': json_url,
'base_url': base_url})
if req_neg.supported:
return HttpResponse(template.render(context))
else:
# client wanted a mimetype we don't support
return HttpResponse(req_neg.error_message,
content_type=req_neg.use_response_type + "; charset=utf8",
status=415)
else:
cache_control(no_cache=True)
template = loader.get_template('500.html')
context = RequestContext(request,
{'error': 'Solr Connection Problem'})
return HttpResponse(template.render(context), status=503)
0
Example 82
Project: django-cms Source File: placeholderadmin.py
@method_decorator(require_POST)
@xframe_options_sameorigin
@transaction.atomic
def copy_plugins(self, request):
"""
POST request should have the following data:
- source_language
- source_placeholder_id
- source_plugin_id (optional)
- target_language
- target_placeholder_id
- target_plugin_id (optional, new parent)
"""
source_language = request.POST['source_language']
source_placeholder_id = request.POST['source_placeholder_id']
source_plugin_id = request.POST.get('source_plugin_id', None)
target_language = request.POST['target_language']
target_placeholder_id = request.POST['target_placeholder_id']
target_plugin_id = request.POST.get('target_plugin_id', None)
source_placeholder = get_object_or_404(Placeholder, pk=source_placeholder_id)
target_placeholder = get_object_or_404(Placeholder, pk=target_placeholder_id)
if not target_language or not target_language in get_language_list():
return HttpResponseBadRequest(force_text(_("Language must be set to a supported language!")))
copy_to_clipboard = target_placeholder.pk == request.toolbar.clipboard.pk
if source_plugin_id:
source_plugin = get_object_or_404(CMSPlugin, pk=source_plugin_id)
reload_required = requires_reload(PLUGIN_COPY_ACTION, [source_plugin])
if source_plugin.plugin_type == "PlaceholderPlugin":
# if it is a PlaceholderReference plugin only copy the plugins it references
inst, cls = source_plugin.get_plugin_instance(self)
plugins = inst.placeholder_ref.get_plugins_list()
else:
plugins = list(
source_placeholder.get_plugins().filter(
path__startswith=source_plugin.path,
depth__gte=source_plugin.depth).order_by('path')
)
else:
plugins = list(
source_placeholder.get_plugins(language=source_language).order_by('path'))
reload_required = requires_reload(PLUGIN_COPY_ACTION, plugins)
if copy_to_clipboard:
has_permissions = self.has_copy_plugins_permission(request, plugins)
else:
# Plugins are being copied from a placeholder in another language
# using the "Copy from language" placeholder action.
# Check if the user can copy plugins from source placeholder to
# target placeholder.
has_permissions = self.has_copy_from_placeholder_permission(
request,
source_placeholder,
target_placeholder,
plugins,
)
if not has_permissions:
return HttpResponseForbidden(force_text(
_('You do not have permission to copy these plugins.')))
if copy_to_clipboard and not source_plugin_id and not target_plugin_id:
# if we copy a whole placeholder to the clipboard create
# PlaceholderReference plugin instead and fill it the content of the
# source_placeholder.
ref = PlaceholderReference()
ref.name = source_placeholder.get_label()
ref.plugin_type = "PlaceholderPlugin"
ref.language = target_language
ref.placeholder = target_placeholder
ref.save()
ref.copy_from(source_placeholder, source_language)
else:
copy_plugins.copy_plugins_to(
plugins, target_placeholder, target_language, target_plugin_id)
plugin_list = CMSPlugin.objects.filter(
language=target_language,
placeholder=target_placeholder
).order_by('path')
reduced_list = []
for plugin in plugin_list:
reduced_list.append(
{
'id': plugin.pk, 'type': plugin.plugin_type, 'parent': plugin.parent_id,
'position': plugin.position, 'desc': force_text(plugin.get_short_description()),
'language': plugin.language, 'placeholder_id': plugin.placeholder_id
}
)
self.post_copy_plugins(request, source_placeholder, target_placeholder, plugins)
# When this is executed we are in the admin class of the source placeholder
# It can be a page or a model with a placeholder field.
# Because of this we need to get the admin class instance of the
# target placeholder and call post_copy_plugins() on it.
# By doing this we make sure that both the source and target are
# informed of the operation.
target_placeholder_admin = self._get_attached_admin(target_placeholder)
if (target_placeholder_admin and
target_placeholder_admin.model != self.model):
target_placeholder_admin.post_copy_plugins(
request,
source_placeholder=source_placeholder,
target_placeholder=target_placeholder,
plugins=plugins,
)
json_response = {'plugin_list': reduced_list, 'reload': reload_required}
return HttpResponse(json.dumps(json_response), content_type='application/json')
0
Example 83
Project: CommunityCellularManager Source File: dashboard.py
def _handle_request(self, request):
"""Process request.
We want filters to persist even when someone changes pages without
re-submitting the form. Page changes will always come over a GET
request, not a POST.
- If it's a GET, we should try to pull settings from the session.
- If it's a POST, we should replace whatever is in the session.
- If it's a GET with no page, we should blank out the session.
"""
profile = UserProfile.objects.get(user=request.user)
network = profile.network
# Process parameters.
# We want filters to persist even when someone changes pages without
# re-submitting the form. Page changes will always come over a GET
# request, not a POST.
# - If it's a GET, we should try to pull settings from the session.
# - If it's a POST, we should replace whatever is in the session.
# - If it's a GET with no page variable, we should blank out the
# session.
if request.method == "POST":
page = 1
request.session['keyword'] = request.POST.get('keyword', None)
request.session['start_date'] = request.POST.get('start_date',
None)
request.session['end_date'] = request.POST.get('end_date', None)
request.session['services'] = request.POST.getlist('services[]',
None)
# We always just do a redirect to GET. We include page reference
# to retain the search parameters in the session.
return redirect(urlresolvers.reverse('network-activity') +
"?page=1")
elif request.method == "GET":
page = request.GET.get('page', 1)
if 'page' not in request.GET:
# Reset filtering params.
request.session['keyword'] = None
request.session['start_date'] = None
request.session['end_date'] = None
request.session['services'] = None
else:
return HttpResponseBadRequest()
# Determine if there has been any activity on the network (if not, we
# won't show the filter boxes).
network_has_activity = UsageEvent.objects.filter(
network=network).exists()
# Read filtering params out of the session.
keyword = request.session['keyword']
start_date = request.session['start_date']
end_date = request.session['end_date']
services = request.session['services']
events = self._get_events(profile, keyword, start_date, end_date,
services)
event_count = events.count()
currency = CURRENCIES[network.subscriber_currency]
# If a CSV has been requested, return that here.
# TODO(shaddi): Kind of a hack, probably should be exposed as REST API
if request.method == "GET" and request.GET.get('csv', False):
headers = [
'Transaction ID',
'Day',
'Time',
'Time Zone',
'Subscriber IMSI',
'BTS Identifier',
'BTS Name',
'Type of Event',
'Description',
'From Number',
'To Number',
'Billable Call Duration (sec)',
'Total Call Duration (sec)',
'Tariff (%s)' % (currency,),
'Cost (%s)' % (currency,),
'Prior Balance (%s)' % (currency,),
'Final Balance (%s)' % (currency,),
'Bytes Uploaded',
'Bytes Downloaded',
]
response = HttpResponse(content_type='text/csv')
# TODO(shaddi): use a filename that captures the search terms?
response['Content-Disposition'] = ('attachment;filename='
'"etage-%s.csv"') \
% (datetime.datetime.now().date(),)
writer = csv.writer(response)
writer.writerow(headers)
# Forcibly limit to 7000 items.
timezone = pytz.timezone(profile.timezone)
for e in events[:7000]:
#first strip the IMSI off if present
subscriber = e.subscriber_imsi
if e.subscriber_imsi.startswith('IMSI'):
subscriber = e.subscriber_imsi[4:]
tz_date = django_utils_timezone.localtime(e.date, timezone)
writer.writerow([
e.transaction_id,
tz_date.date().strftime("%m-%d-%Y"),
tz_date.time().strftime("%I:%M:%S %p"),
timezone,
subscriber,
e.bts_uuid,
e.bts.nickname,
e.kind,
e.reason,
e.from_number,
e.to_number,
e.billsec,
e.call_duration,
humanize_credits(e.tariff, currency=currency).amount_str()
if e.tariff else None,
humanize_credits(e.change, currency=currency).amount_str()
if e.change else None,
humanize_credits(e.oldamt, currency=currency).amount_str()
if e.oldamt else None,
humanize_credits(e.newamt, currency=currency).amount_str()
if e.newamt else None,
e.uploaded_bytes,
e.downloaded_bytes,
])
return response
# Otherwise, we paginate.
event_paginator = Paginator(events, 25)
try:
events = event_paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
events = event_paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 999), deliver last page of results.
events = event_paginator.page(event_paginator.num_pages)
# Setup the context for the template.
context = {
'networks': get_objects_for_user(request.user, 'view_network', klass=Network),
'currency': CURRENCIES[network.subscriber_currency],
'user_profile': profile,
'network_has_activity': network_has_activity,
'events': events,
'event_count': event_count,
}
# Setup various stuff for filter form generation.
service_names = ["SMS", "Call", "GPRS", "Transfer", "Other"]
if not services:
context['service_types'] = [
("SMS", True),
("Call", True),
("GPRS", True),
("Transfer", True),
("Other", True)
]
else:
context['service_types'] = []
for name in service_names:
if name.lower() in services:
context['service_types'].append((name, True))
else:
context['service_types'].append((name, False))
context['eventfilter'] = {
'keyword': keyword,
'start_date': start_date,
'end_date': end_date
}
template = get_template('dashboard/activity.html')
html = template.render(context, request)
return HttpResponse(html)
0
Example 84
Project: django-nonrel Source File: i18n.py
def javascript_catalog(request, domain='djangojs', packages=None):
"""
Returns the selected language catalog as a javascript library.
Receives the list of packages to check for translations in the
packages parameter either from an infodict or as a +-delimited
string from the request. Default is 'django.conf'.
Additionally you can override the gettext domain for this view,
but usually you don't want to do that, as JavaScript messages
go to the djangojs domain. But this might be needed if you
deliver your JavaScript source from Django templates.
"""
if request.GET:
if 'language' in request.GET:
if check_for_language(request.GET['language']):
activate(request.GET['language'])
if packages is None:
packages = ['django.conf']
if isinstance(packages, basestring):
packages = packages.split('+')
packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
default_locale = to_locale(settings.LANGUAGE_CODE)
locale = to_locale(get_language())
t = {}
paths = []
en_selected = locale.startswith('en')
en_catalog_missing = True
# paths of requested packages
for package in packages:
p = importlib.import_module(package)
path = os.path.join(os.path.dirname(p.__file__), 'locale')
paths.append(path)
# add the filesystem paths listed in the LOCALE_PATHS setting
paths.extend(list(reversed(settings.LOCALE_PATHS)))
# first load all english languages files for defaults
for path in paths:
try:
catalog = gettext_module.translation(domain, path, ['en'])
t.update(catalog._catalog)
except IOError:
pass
else:
# 'en' is the selected language and at least one of the packages
# listed in `packages` has an 'en' catalog
if en_selected:
en_catalog_missing = False
# next load the settings.LANGUAGE_CODE translations if it isn't english
if default_locale != 'en':
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [default_locale])
except IOError:
catalog = None
if catalog is not None:
t.update(catalog._catalog)
# last load the currently selected language, if it isn't identical to the default.
if locale != default_locale:
# If the currently selected language is English but it doesn't have a
# translation catalog (presumably due to being the language translated
# from) then a wrong language catalog might have been loaded in the
# previous step. It needs to be discarded.
if en_selected and en_catalog_missing:
t = {}
else:
locale_t = {}
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [locale])
except IOError:
catalog = None
if catalog is not None:
locale_t.update(catalog._catalog)
if locale_t:
t = locale_t
src = [LibHead]
plural = None
if '' in t:
for l in t[''].split('\n'):
if l.startswith('Plural-Forms:'):
plural = l.split(':',1)[1].strip()
if plural is not None:
# this should actually be a compiled function of a typical plural-form:
# Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=',1)[1]
src.append(PluralIdx % plural)
else:
src.append(SimplePlural)
csrc = []
pdict = {}
for k, v in t.items():
if k == '':
continue
if isinstance(k, basestring):
csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
elif isinstance(k, tuple):
if k[0] not in pdict:
pdict[k[0]] = k[1]
else:
pdict[k[0]] = max(k[1], pdict[k[0]])
csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
else:
raise TypeError(k)
csrc.sort()
for k, v in pdict.items():
src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1))))
src.extend(csrc)
src.append(LibFoot)
src.append(InterPolate)
src.append(LibFormatHead)
src.append(get_formats())
src.append(LibFormatFoot)
src = ''.join(src)
return http.HttpResponse(src, 'text/javascript')
0
Example 85
Project: aemanager Source File: views.py
@csrf_exempt
@commit_on_success
def paypal_ipn(request):
# send back the response to paypal
data = dict(request.POST.items())
args = {'cmd': '_notify-validate'}
args.update(data)
params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in args.items()))
paypal_response = urllib2.urlopen(settings.PAYPAL_URL + '/cgi-bin/webscr', params).read()
# process the payment
receiver_id = data['receiver_id']
transaction_id = data['txn_id']
payment_status = data['payment_status']
payment_amount = data['mc_gross']
payment_currency = data['mc_currency']
fee = data['mc_fee']
item_name = data['item_name']
user_id = data['custom']
user = get_object_or_404(User, pk=user_id)
profile = user.get_profile()
last_subscription = profile.get_last_subscription()
subscription, created = Subscription.objects.get_or_create(transaction_id=transaction_id,
defaults={'owner': user,
'state': SUBSCRIPTION_STATE_NOT_PAID,
'expiration_date': profile.get_next_expiration_date(),
'transaction_id': transaction_id,
'error_message': ugettext('Not verified')})
if paypal_response == 'VERIFIED':
if receiver_id <> settings.PAYPAL_RECEIVER_ID:
subscription.error_message = ugettext('Receiver is not as defined in settings. Spoofing ?')
elif payment_status <> 'Completed':
subscription.error_message = ugettext('Payment not completed')
elif payment_amount <> settings.PAYPAL_APP_SUBSCRIPTION_AMOUNT:
subscription.error_message = ugettext('Amount altered. Bad guy ?')
elif payment_currency <> settings.PAYPAL_APP_SUBSCRIPTION_CURRENCY:
subscription.error_message = ugettext('Amount altered. Bad guy ?')
else:
subscription.error_message = ugettext('Paid')
subscription.state = SUBSCRIPTION_STATE_PAID
# create an invoice for this payment
# first, get the provider user
provider = User.objects.get(email=settings.SERVICE_PROVIDER_EMAIL)
if provider.get_profile().vat_number:
payment_amount = Decimal(payment_amount) / Decimal('1.196')
# look for a customer corresponding to user
address, created = Address.objects.get_or_create(contact__email=user.email,
owner=provider,
defaults={'street': profile.address.street,
'zipcode': profile.address.zipcode,
'city': profile.address.city,
'country': profile.address.country,
'owner': provider})
customer, created = Contact.objects.get_or_create(email=user.email,
defaults={'contact_type': CONTACT_TYPE_COMPANY,
'name': '%s %s' % (user.first_name, user.last_name),
'company_id': profile.company_id,
'legal_form': 'Auto-entrepreneur',
'email': user.email,
'address': address,
'owner': provider})
# create a related project if needed
# set it to finished to clear daily business
project, created = Project.objects.get_or_create(state=PROJECT_STATE_FINISHED,
customer=customer,
name='Subscription %s - %s %s' % (Site.objects.get_current().name, user.first_name, user.last_name),
defaults={'state': PROJECT_STATE_FINISHED,
'customer': customer,
'name': 'Subscription %s - %s %s' % (Site.objects.get_current().name, user.first_name, user.last_name),
'owner': provider})
# create proposal for this subscription
begin_date = datetime.date.today()
if begin_date < last_subscription.expiration_date:
begin_date = last_subscription.expiration_date
proposal = Proposal.objects.create(project=project,
reference='subscription%i%i%i' % (subscription.expiration_date.year,
subscription.expiration_date.month,
subscription.expiration_date.day),
state=PROPOSAL_STATE_BALANCED,
begin_date=begin_date,
end_date=subscription.expiration_date,
contract_content='',
update_date=datetime.date.today(),
expiration_date=None,
owner=provider)
unit_price = Decimal(settings.PAYPAL_APP_SUBSCRIPTION_AMOUNT)
if provider.get_profile().vat_number:
unit_price = Decimal(unit_price) / Decimal('1.196')
proposal_row = ProposalRow.objects.create(proposal=proposal,
label=item_name,
category=ROW_CATEGORY_SERVICE,
quantity=1,
unit_price='%s' % unit_price,
owner=provider)
# finally create invoice
invoice = Invoice.objects.create(customer=customer,
invoice_id=Invoice.objects.get_next_invoice_id(provider),
state=INVOICE_STATE_PAID,
amount=payment_amount,
edition_date=datetime.date.today(),
payment_date=datetime.date.today(),
paid_date=datetime.date.today(),
payment_type=PAYMENT_TYPE_BANK_CARD,
execution_begin_date=begin_date,
execution_end_date=subscription.expiration_date,
penalty_date=None,
penalty_rate=None,
discount_conditions=None,
owner=provider)
invoice_row = InvoiceRow.objects.create(proposal=proposal,
invoice=invoice,
label=item_name,
category=ROW_CATEGORY_SERVICE,
quantity=1,
unit_price=payment_amount,
balance_payments=True,
vat_rate=VAT_RATES_19_6,
owner=provider)
# create expense for paypal fee
expense = Expense.objects.create(date=datetime.date.today(),
reference=transaction_id,
supplier='Paypal',
amount=fee,
payment_type=PAYMENT_TYPE_BANK_CARD,
description='Commission paypal',
owner=provider)
# generate invoice in pdf
response = HttpResponse(mimetype='application/pdf')
invoice.to_pdf(provider, response)
subject_template = loader.get_template('core/subscription_paid_email_subject.html')
subject_context = {'site_name': Site.objects.get_current().name}
subject = subject_template.render(Context(subject_context))
body_template = loader.get_template('core/subscription_paid_email.html')
body_context = {'site_name': Site.objects.get_current().name,
'expiration_date': subscription.expiration_date}
body = body_template.render(Context(body_context))
email = EmailMessage(subject=subject,
body=body,
to=[user.email])
email.attach('facture_%i.pdf' % (invoice.invoice_id), response.content, 'application/pdf')
email.send(fail_silently=(not settings.DEBUG))
subscription.save()
return render_to_response('core/paypal_ipn.html',
{'active': 'account',
'title': _('Subscribe')},
context_instance=RequestContext(request))
0
Example 86
Project: django-cms Source File: views.py
def details(request, slug):
"""
The main view of the Django-CMS! Takes a request and a slug, renders the
page.
"""
response_timestamp = now()
if get_cms_setting("PAGE_CACHE") and (
not hasattr(request, 'toolbar') or (
not request.toolbar.edit_mode and
not request.toolbar.show_toolbar and
not request.user.is_authenticated()
)
):
cache_content = get_page_cache(request)
if cache_content is not None:
content, headers, expires_datetime = cache_content
response = HttpResponse(content)
response._headers = headers
# Recalculate the max-age header for this cached response
max_age = int(
(expires_datetime - response_timestamp).total_seconds() + 0.5)
patch_cache_control(response, max_age=max_age)
return response
# Get a Page model object from the request
page = get_page_from_request(request, use_path=slug)
if not page:
return _handle_no_page(request, slug)
current_language = request.GET.get('language', None)
if not current_language:
current_language = request.POST.get('language', None)
if current_language:
current_language = get_language_code(current_language)
if current_language not in get_language_list(page.site_id):
current_language = None
if current_language is None:
current_language = get_language_code(getattr(request, 'LANGUAGE_CODE', None))
if current_language:
current_language = get_language_code(current_language)
if current_language not in get_language_list(page.site_id):
current_language = None
if current_language is None:
current_language = get_language_code(get_language())
# Check that the current page is available in the desired (current) language
available_languages = []
# this will return all languages in draft mode, and published only in live mode
page_languages = list(page.get_published_languages())
if hasattr(request, 'user') and request.user.is_staff:
user_languages = get_language_list()
else:
user_languages = get_public_languages()
for frontend_lang in user_languages:
if frontend_lang in page_languages:
available_languages.append(frontend_lang)
# Check that the language is in FRONTEND_LANGUAGES:
own_urls = [
'http%s://%s%s' % ('s' if request.is_secure() else '', request.get_host(), request.path),
'/%s' % request.path,
request.path,
]
if current_language not in user_languages:
#are we on root?
if not slug:
#redirect to supported language
languages = []
for language in available_languages:
languages.append((language, language))
if languages:
# get supported language
new_language = get_language_from_request(request)
if new_language in get_public_languages():
with force_language(new_language):
pages_root = reverse('pages-root')
if (hasattr(request, 'toolbar') and request.user.is_staff and request.toolbar.edit_mode):
request.toolbar.redirect_url = pages_root
elif pages_root not in own_urls:
return HttpResponseRedirect(pages_root)
elif not hasattr(request, 'toolbar') or not request.toolbar.redirect_url:
_handle_no_page(request, slug)
else:
return _handle_no_page(request, slug)
if current_language not in available_languages:
# If we didn't find the required page in the requested (current)
# language, let's try to find a fallback
found = False
for alt_lang in get_fallback_languages(current_language):
if alt_lang in available_languages:
if get_redirect_on_fallback(current_language) or slug == "":
with force_language(alt_lang):
path = page.get_absolute_url(language=alt_lang, fallback=True)
# In the case where the page is not available in the
# preferred language, *redirect* to the fallback page. This
# is a design decision (instead of rendering in place)).
if (hasattr(request, 'toolbar') and request.user.is_staff
and request.toolbar.edit_mode):
request.toolbar.redirect_url = path
elif path not in own_urls:
return HttpResponseRedirect(path)
else:
found = True
if not found and (not hasattr(request, 'toolbar') or not request.toolbar.redirect_url):
# There is a page object we can't find a proper language to render it
_handle_no_page(request, slug)
else:
page_path = page.get_absolute_url(language=current_language)
page_slug = page.get_path(language=current_language) or page.get_slug(language=current_language)
if slug and slug != page_slug and request.path[:len(page_path)] != page_path:
# The current language does not match it's slug.
# Redirect to the current language.
if hasattr(request, 'toolbar') and request.user.is_staff and request.toolbar.edit_mode:
request.toolbar.redirect_url = page_path
else:
return HttpResponseRedirect(page_path)
if apphook_pool.get_apphooks():
# There are apphooks in the pool. Let's see if there is one for the
# current page
# since we always have a page at this point, applications_page_check is
# pointless
# page = applications_page_check(request, page, slug)
# Check for apphooks! This time for real!
app_urls = page.get_application_urls(current_language, False)
skip_app = False
if (not page.is_published(current_language) and hasattr(request, 'toolbar')
and request.toolbar.edit_mode):
skip_app = True
if app_urls and not skip_app:
app = apphook_pool.get_apphook(app_urls)
pattern_list = []
if app:
for urlpatterns in get_app_urls(app.get_urls(page, current_language)):
pattern_list += urlpatterns
try:
view, args, kwargs = resolve('/', tuple(pattern_list))
return view(request, *args, **kwargs)
except Resolver404:
pass
# Check if the page has a redirect url defined for this language.
redirect_url = page.get_redirect(language=current_language)
if redirect_url:
if (is_language_prefix_patterns_used() and redirect_url[0] == "/"
and not redirect_url.startswith('/%s/' % current_language)):
# add language prefix to url
redirect_url = "/%s/%s" % (current_language, redirect_url.lstrip("/"))
# prevent redirect to self
if hasattr(request, 'toolbar') and request.user.is_staff and request.toolbar.edit_mode:
request.toolbar.redirect_url = redirect_url
elif redirect_url not in own_urls:
return HttpResponseRedirect(redirect_url)
# permission checks
if page.login_required and not request.user.is_authenticated():
return redirect_to_login(urlquote(request.get_full_path()), settings.LOGIN_URL)
if hasattr(request, 'toolbar'):
request.toolbar.set_object(page)
response = render_page(request, page, current_language=current_language, slug=slug)
return response
0
Example 87
Project: lettuce Source File: i18n.py
def javascript_catalog(request, domain='djangojs', packages=None):
"""
Returns the selected language catalog as a javascript library.
Receives the list of packages to check for translations in the
packages parameter either from an infodict or as a +-delimited
string from the request. Default is 'django.conf'.
Additionally you can override the gettext domain for this view,
but usually you don't want to do that, as JavaScript messages
go to the djangojs domain. But this might be needed if you
deliver your JavaScript source from Django templates.
"""
if request.GET:
if 'language' in request.GET:
if check_for_language(request.GET['language']):
activate(request.GET['language'])
if packages is None:
packages = ['django.conf']
if isinstance(packages, basestring):
packages = packages.split('+')
packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
default_locale = to_locale(settings.LANGUAGE_CODE)
locale = to_locale(get_language())
t = {}
paths = []
en_selected = locale.startswith('en')
en_catalog_missing = True
# first load all english languages files for defaults
for package in packages:
p = importlib.import_module(package)
path = os.path.join(os.path.dirname(p.__file__), 'locale')
paths.append(path)
try:
catalog = gettext_module.translation(domain, path, ['en'])
t.update(catalog._catalog)
except IOError:
pass
else:
# 'en' is the selected language and at least one of the packages
# listed in `packages` has an 'en' catalog
if en_selected:
en_catalog_missing = False
# next load the settings.LANGUAGE_CODE translations if it isn't english
if default_locale != 'en':
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [default_locale])
except IOError:
catalog = None
if catalog is not None:
t.update(catalog._catalog)
# last load the currently selected language, if it isn't identical to the default.
if locale != default_locale:
# If the currently selected language is English but it doesn't have a
# translation catalog (presumably due to being the language translated
# from) then a wrong language catalog might have been loaded in the
# previous step. It needs to be discarded.
if en_selected and en_catalog_missing:
t = {}
else:
locale_t = {}
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [locale])
except IOError:
catalog = None
if catalog is not None:
locale_t.update(catalog._catalog)
if locale_t:
t = locale_t
src = [LibHead]
plural = None
if '' in t:
for l in t[''].split('\n'):
if l.startswith('Plural-Forms:'):
plural = l.split(':',1)[1].strip()
if plural is not None:
# this should actually be a compiled function of a typical plural-form:
# Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=',1)[1]
src.append(PluralIdx % plural)
else:
src.append(SimplePlural)
csrc = []
pdict = {}
for k, v in t.items():
if k == '':
continue
if isinstance(k, basestring):
csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
elif isinstance(k, tuple):
if k[0] not in pdict:
pdict[k[0]] = k[1]
else:
pdict[k[0]] = max(k[1], pdict[k[0]])
csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
else:
raise TypeError(k)
csrc.sort()
for k, v in pdict.items():
src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1))))
src.extend(csrc)
src.append(LibFoot)
src.append(InterPolate)
src.append(LibFormatHead)
src.append(get_formats())
src.append(LibFormatFoot)
src = ''.join(src)
return http.HttpResponse(src, 'text/javascript')
0
Example 88
Project: django-flatpages-plus Source File: views.py
@csrf_protect
def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If the page is a draft, only show it to users who are staff.
if f.status == 'd' and not request.user.is_authenticated():
raise Http404
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated():
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.path)
if f.template_name:
t = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
else:
t = loader.get_template(DEFAULT_TEMPLATE)
# Track pageviews (but not of owner).
if request.user != f.owner:
f.views += 1
f.save()
# To avoid having to always use the "|safe" filter in flatpage templates,
# mark the title and content as already safe (since they are raw HTML
# content in the first place).
f.title = mark_safe(f.title)
f.content = mark_safe(f.content)
# Create breadcrumb navigation links.
# breadcrumb_urls = f.url.lstrip('/').rstrip('/').split('/')
# breadcrumb_urls.insert(0, '/')
#
# for i, u in enumerate(breadcrumb_urls):
# try: # Try and get a flatpage instance from the URL.
# if u != '/':
# u = '/%s/' % u
# fp = FlatPage.objects.get(url__exact=u)
# bt = fp.title
# bu = fp.url
# except: # Default to the URL slug, capitalized if no flatpage was found.
# bt = u.capitalize()
# bu = None
# breadcrumbs += [{ # Contsruct a dictionary for the breadcrumb entity.
# 'url': bu,
# 'title': bt,
# }]
breadcrumb_urls = []
breadcrumbs = []
def trim_page(url):
"""Trim the last section off a URL."""
regex = re.compile(r'(?P<url>.*/)[-\w\.]+/?$')
try:
trimmed_url = regex.match(url).group('url') # Return the parent page
except:
trimmed_url = None # Return None to indicate no parent.
return trimmed_url
def do_trimming(url):
"""Perform the trimming operations recursively."""
breadcrumb_urls.append(url)
trimmed_url = trim_page(url)
if trimmed_url:
do_trimming(trimmed_url)
else:
return True
# Trim the flatpage's URL.
do_trimming(f.url)
# Reverse the list of breadcrumbs so the parent pages start first.
breadcrumb_urls.reverse()
# Loop through the list of pages and construct a list of url/title dictionaries
# for each page to use in the templates.
for i, u in enumerate(breadcrumb_urls):
bn = ''
bu = ''
try: # Try and get a flatpage instance from the URL.
# if u != '/':
# u = '/%s/' % u
fp = FlatPage.objects.get(url__exact=u)
bn = fp.name
bu = fp.url
except: # Try to handle missing pages cleanly.
regex = re.compile(r'.*/(?P<url>[-\w\.]+)/?$')
try:
# Default to the URL slug of the last segment of the URL
# (capitalized) if no flatpage was found. This gives us an
# OK default for missing pages.
bn = regex.match(u).group('url')
except:
# Worst case scenario we show the URL as the title if we can't
# grab the last bit of the URL...
bn = u
bn = bn.capitalize() # Capitalize it to make it look a little nicer.
# Return None if the flatpage doesn't exist so we don't link to it,
# because it would cause a 404 error if we did.
bu = None
breadcrumbs += [{ # Contsruct a dictionary for the breadcrumb entity.
'url': bu,
'name': bn,
}]
c = RequestContext(request, {
'flatpage': f,
'breadcrumbs': breadcrumbs,
})
response = HttpResponse(t.render(c))
populate_xheaders(request, response, FlatPage, f.id)
return response
0
Example 89
Project: geonode Source File: views.py
@login_required
def layer_metadata(request, layername, template='layers/layer_metadata.html'):
layer = _resolve_layer(
request,
layername,
'base.change_resourcebase_metadata',
_PERMISSION_MSG_METADATA)
layer_attribute_set = inlineformset_factory(
Layer,
Attribute,
extra=0,
form=LayerAttributeForm,
)
topic_category = layer.category
poc = layer.poc
metadata_author = layer.metadata_author
if request.method == "POST":
if layer.metadata_uploaded_preserve: # layer metadata cannot be edited
out = {
'success': False,
'errors': METADATA_UPLOADED_PRESERVE_ERROR
}
return HttpResponse(
json.dumps(out),
content_type='application/json',
status=400)
layer_form = LayerForm(request.POST, instance=layer, prefix="resource")
attribute_form = layer_attribute_set(
request.POST,
instance=layer,
prefix="layer_attribute_set",
queryset=Attribute.objects.order_by('display_order'))
category_form = CategoryForm(
request.POST,
prefix="category_choice_field",
initial=int(
request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None)
else:
layer_form = LayerForm(instance=layer, prefix="resource")
attribute_form = layer_attribute_set(
instance=layer,
prefix="layer_attribute_set",
queryset=Attribute.objects.order_by('display_order'))
category_form = CategoryForm(
prefix="category_choice_field",
initial=topic_category.id if topic_category else None)
if request.method == "POST" and layer_form.is_valid(
) and attribute_form.is_valid() and category_form.is_valid():
new_poc = layer_form.cleaned_data['poc']
new_author = layer_form.cleaned_data['metadata_author']
if new_poc is None:
if poc is None:
poc_form = ProfileForm(
request.POST,
prefix="poc",
instance=poc)
else:
poc_form = ProfileForm(request.POST, prefix="poc")
if poc_form.is_valid():
if len(poc_form.cleaned_data['profile']) == 0:
# FIXME use form.add_error in django > 1.7
errors = poc_form._errors.setdefault('profile', ErrorList())
errors.append(_('You must set a point of contact for this resource'))
poc = None
if poc_form.has_changed and poc_form.is_valid():
new_poc = poc_form.save()
if new_author is None:
if metadata_author is None:
author_form = ProfileForm(request.POST, prefix="author",
instance=metadata_author)
else:
author_form = ProfileForm(request.POST, prefix="author")
if author_form.is_valid():
if len(author_form.cleaned_data['profile']) == 0:
# FIXME use form.add_error in django > 1.7
errors = author_form._errors.setdefault('profile', ErrorList())
errors.append(_('You must set an author for this resource'))
metadata_author = None
if author_form.has_changed and author_form.is_valid():
new_author = author_form.save()
new_category = TopicCategory.objects.get(
id=category_form.cleaned_data['category_choice_field'])
for form in attribute_form.cleaned_data:
la = Attribute.objects.get(id=int(form['id'].id))
la.description = form["description"]
la.attribute_label = form["attribute_label"]
la.visible = form["visible"]
la.display_order = form["display_order"]
la.save()
if new_poc is not None and new_author is not None:
new_keywords = [x.strip() for x in layer_form.cleaned_data['keywords']]
layer.keywords.clear()
layer.keywords.add(*new_keywords)
the_layer = layer_form.save()
up_sessions = UploadSession.objects.filter(layer=the_layer.id)
if up_sessions.count() > 0 and up_sessions[0].user != the_layer.owner:
up_sessions.update(user=the_layer.owner)
the_layer.poc = new_poc
the_layer.metadata_author = new_author
Layer.objects.filter(id=the_layer.id).update(
category=new_category
)
if getattr(settings, 'SLACK_ENABLED', False):
try:
from geonode.contrib.slack.utils import build_slack_message_layer, send_slack_messages
send_slack_messages(build_slack_message_layer("layer_edit", the_layer))
except:
print "Could not send slack message."
return HttpResponseRedirect(
reverse(
'layer_detail',
args=(
layer.service_typename,
)))
if poc is not None:
layer_form.fields['poc'].initial = poc.id
poc_form = ProfileForm(prefix="poc")
poc_form.hidden = True
else:
poc_form = ProfileForm(prefix="poc")
poc_form.hidden = False
if metadata_author is not None:
layer_form.fields['metadata_author'].initial = metadata_author.id
author_form = ProfileForm(prefix="author")
author_form.hidden = True
else:
author_form = ProfileForm(prefix="author")
author_form.hidden = False
return render_to_response(template, RequestContext(request, {
"layer": layer,
"layer_form": layer_form,
"poc_form": poc_form,
"author_form": author_form,
"attribute_form": attribute_form,
"category_form": category_form,
}))
0
Example 90
def object_list(request, queryset, paginate_by=None, page=None,
allow_empty=True, template_name=None, template_loader=loader,
extra_context=None, template_object_name='object', content_type=None):
"""
Generic list of objects.
Templates: ``<app_label>/<model_name>_list.html``
Context:
object_list
list of objects
is_paginated
are the results paginated?
results_per_page
number of objects per page (if paginated)
has_next
is there a next page?
has_previous
is there a prev page?
page
the current page
next
the next page
previous
the previous page
pages
number of pages, total
hits
number of objects, total
last_on_page
the result number of the last of object in the
object_list (1-indexed)
first_on_page
the result number of the first object in the
object_list (1-indexed)
page_range:
A list of the page numbers (1-indexed).
"""
if extra_context is None:
extra_context = {}
queryset = queryset._clone()
if paginate_by:
paginator = Paginator(queryset, paginate_by,
allow_empty_first_page=allow_empty)
if not page:
page = request.GET.get('page', 1)
try:
page_number = int(page)
except ValueError:
if page == 'last':
page_number = paginator.num_pages
else:
# Page is not 'last', nor can it be converted to an int.
raise Http404
try:
page_obj = paginator.page(page_number)
except InvalidPage:
raise Http404
try:
next_page = page_obj.next_page_number()
except InvalidPage:
next_page = None
try:
previous_page = page_obj.previous_page_number()
except InvalidPage:
previous_page = None
c = {
'%s_list' % template_object_name: page_obj.object_list,
'paginator': paginator,
'page_obj': page_obj,
'is_paginated': page_obj.has_other_pages(),
# Legacy template context stuff. New templates should use page_obj
# to access this instead.
'results_per_page': paginator.per_page,
'has_next': page_obj.has_next(),
'has_previous': page_obj.has_previous(),
'page': page_obj.number,
'next': next_page,
'previous': previous_page,
'first_on_page': page_obj.start_index(),
'last_on_page': page_obj.end_index(),
'pages': paginator.num_pages,
'hits': paginator.count,
'page_range': paginator.page_range,
}
else:
c = {
'%s_list' % template_object_name: queryset,
'paginator': None,
'page_obj': None,
'is_paginated': False,
}
if not allow_empty and len(queryset) == 0:
raise Http404
for key, value in extra_context.items():
if callable(value):
c[key] = value()
else:
c[key] = value
if not template_name:
model = queryset.model
template_name = "%s/%s_list.html" % (model._meta.app_label,
model._meta.object_name.lower())
t = template_loader.get_template(template_name)
return HttpResponse(t.render(c, request=request), content_type=content_type)
0
Example 91
Project: sentry Source File: error_page_embed.py
@csrf_exempt
def dispatch(self, request):
try:
event_id = request.GET['eventId']
except KeyError:
return self._json_response(request, status=400)
if not is_event_id(event_id):
return self._json_response(request, status=400)
key = self._get_project_key(request)
if not key:
return self._json_response(request, status=404)
origin = self._get_origin(request)
if not origin:
return self._json_response(request, status=403)
if not is_valid_origin(origin, key.project):
return HttpResponse(status=403)
if request.method == 'OPTIONS':
return self._json_response(request)
# TODO(dcramer): since we cant use a csrf cookie we should at the very
# least sign the request / add some kind of nonce
initial = {
'name': request.GET.get('name'),
'email': request.GET.get('email'),
}
form = UserReportForm(request.POST if request.method == 'POST' else None,
initial=initial)
if form.is_valid():
# TODO(dcramer): move this to post to the internal API
report = form.save(commit=False)
report.project = key.project
report.event_id = event_id
try:
mapping = EventMapping.objects.get(
event_id=report.event_id,
project_id=key.project_id,
)
except EventMapping.DoesNotExist:
# XXX(dcramer): the system should fill this in later
pass
else:
report.group = Group.objects.get(id=mapping.group_id)
try:
with transaction.atomic():
report.save()
except IntegrityError:
# There was a duplicate, so just overwrite the existing
# row with the new one. The only way this ever happens is
# if someone is messing around with the API, or doing
# something wrong with the SDK, but this behavior is
# more reasonable than just hard erroring and is more
# expected.
UserReport.objects.filter(
project=report.project,
event_id=report.event_id,
).update(
name=report.name,
email=report.email,
comments=report.comments,
date_added=timezone.now(),
)
return self._json_response(request)
elif request.method == 'POST':
return self._json_response(request, {
"errors": dict(form.errors),
}, status=400)
show_branding = ProjectOption.objects.get_value(
project=key.project,
key='feedback:branding',
default='1'
) == '1'
template = render_to_string('sentry/error-page-embed.html', {
'form': form,
'show_branding': show_branding,
})
context = {
'endpoint': mark_safe('*/' + json.dumps(request.build_absolute_uri()) + ';/*'),
'template': mark_safe('*/' + json.dumps(template) + ';/*'),
'strings': json.dumps_htmlsafe({
'generic_error': six.text_type(GENERIC_ERROR),
'form_error': six.text_type(FORM_ERROR),
'sent_message': six.text_type(SENT_MESSAGE),
}),
}
return render_to_response('sentry/error-page-embed.js', context, request,
content_type='text/javascript')
0
Example 92
Project: django-dynamic-choices Source File: admin.py
def dynamic_admin_factory(admin_cls):
change_form_template = 'admin/dynamic_choices/change_form.html'
class meta_cls(type(admin_cls)):
"Metaclass that ensure form and inlines are dynamic"
def __new__(cls, name, bases, attrs):
# If there's already a form defined we make sure to subclass it
if 'form' in attrs:
attrs['form'] = dynamic_model_form_factory(attrs['form'])
else:
attrs['form'] = DynamicModelForm
# Make sure the specified add|change_form_template
# extends "admin/dynamic_choices/change_form.html"
for t, default in [('add_form_template', None),
('change_form_template', change_form_template)]:
if t in attrs:
if not template_extends(attrs[t], change_form_template):
raise ImproperlyConfigured(
"Make sure %s.%s template extends '%s' in order to enable DynamicAdmin" % (
name, t, change_form_template
)
)
else:
attrs[t] = default
# If there's some inlines defined we make sure that their form is dynamic
# see dynamic_inline_factory
if 'inlines' in attrs:
attrs['inlines'] = [dynamic_inline_factory(inline_cls) for inline_cls in attrs['inlines']]
return super(meta_cls, cls).__new__(cls, name, bases, attrs)
class cls(with_metaclass(meta_cls, admin_cls)):
def _media(self):
media = super(cls, self).media
media.add_js(('js/dynamic-choices.js',
'js/dynamic-choices-admin.js'))
return media
media = property(_media)
def get_urls(self):
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.model_name
urlpatterns = [
url(r'(?:add|(?P<object_id>\w+))/choices/$',
wrap(self.dynamic_choices),
name="%s_%s_dynamic_admin" % info),
] + super(cls, self).get_urls()
return urlpatterns
def get_dynamic_choices_binder(self, request):
def id(field):
return "[name='%s']" % field
def inline_field_selector(fieldset, field):
return "[name^='%s-'][name$='-%s']" % (fieldset, field)
fields = {}
def add_fields(to_fields, to_field, bind_fields):
if not (to_field in to_fields):
to_fields[to_field] = set()
to_fields[to_field].update(bind_fields)
model_name = self.model._meta.model_name
# Use get_form in order to allow formfield override
# We should create a fake request from referer but all this
# hack will be fixed when the code is embed directly in the page
form = self.get_form(request)()
rels = form.get_dynamic_relationships()
for rel in rels:
field_name = rel.split(LOOKUP_SEP)[0]
if rel in form.fields:
add_fields(fields, id(field_name), [id(field) for field in rels[rel] if field in form.fields])
inlines = {}
for formset, _inline in self.get_formsets_with_inlines(request):
inline = {}
formset_form = formset.form()
inline_rels = formset_form.get_dynamic_relationships()
prefix = formset.get_default_prefix()
for rel in inline_rels:
if LOOKUP_SEP in rel:
base, field = rel.split(LOOKUP_SEP)[0:2]
if base == model_name and field in form.fields:
bound_fields = [
inline_field_selector(prefix, f)
for f in inline_rels[rel] if f in formset_form.fields
]
add_fields(fields, id(field), bound_fields)
elif base in formset_form.fields:
add_fields(inline, base, inline_rels[rel])
elif rel in formset_form.fields:
add_fields(inline, rel, inline_rels[rel])
if len(inline):
inlines[prefix] = inline
# Replace sets in order to allow JSON serialization
for field, bound_fields in fields.items():
fields[field] = list(bound_fields)
for fieldset, inline_fields in inlines.items():
for field, bound_fields in inline_fields.items():
inlines[fieldset][field] = list(bound_fields)
return SafeText("django.dynamicAdmin(%s, %s);" % (json.dumps(fields), json.dumps(inlines)))
def dynamic_choices(self, request, object_id=None):
opts = self.model._meta
obj = self.get_object(request, object_id)
# Make sure the specified object exists
if object_id is not None and obj is None:
raise Http404('%(name)s object with primary key %(key)r does not exist.' % {
'name': force_text(opts.verbose_name), 'key': escape(object_id)})
form = self.get_form(request)(request.GET, instance=obj)
data = get_dynamic_choices_from_form(form)
for formset, _inline in self.get_formsets_with_inlines(request, obj):
prefix = formset.get_default_prefix()
try:
fs = formset(request.GET, instance=obj)
forms = fs.forms + [fs.empty_form]
except ValidationError:
return HttpResponseBadRequest("Missing %s ManagementForm data" % prefix)
for form in forms:
data.update(get_dynamic_choices_from_form(form))
if 'DYNAMIC_CHOICES_FIELDS' in request.GET:
fields = request.GET.get('DYNAMIC_CHOICES_FIELDS').split(',')
for field in list(data):
if field not in fields:
del data[field]
return HttpResponse(lazy_encoder.encode(data), content_type='application/json')
if django.VERSION >= (1, 7):
_get_formsets_with_inlines = admin_cls.get_formsets_with_inlines
else:
def _get_formsets_with_inlines(self, request, obj=None):
formsets = super(cls, self).get_formsets(request, obj)
inlines = self.get_inline_instances(request, obj)
for formset, inline in zip(formsets, inlines):
yield formset, inline
def get_formsets(self, request, obj=None):
for formset, _inline in self.get_formsets_with_inlines(request, obj):
yield formset
def get_formsets_with_inlines(self, request, obj=None):
# Make sure to pass request data to fieldsets
# so they can use it to define choices
initial = {}
model = self.model
opts = model._meta
data = getattr(request, request.method).items()
# If an object is provided we collect data
if obj is not None:
initial.update(model_to_dict(obj))
# Make sure to collect parent model data
# and provide it to fieldsets in the form of
# parent__field from request if its provided.
# This data should be more "up-to-date".
for k, v in data:
if v:
try:
f = opts.get_field(k)
except models.FieldDoesNotExist:
continue
if isinstance(f, models.ManyToManyField):
initial[k] = v.split(",")
else:
initial[k] = v
for formset, inline in self._get_formsets_with_inlines(request, obj):
fk = _get_foreign_key(self.model, inline.model, fk_name=inline.fk_name).name
fk_initial = dict(('%s__%s' % (fk, k), v) for k, v in initial.items())
# If we must provide additional data
# we must wrap the formset in a subclass
# because passing 'initial' key argument is intercepted
# and not provided to subclasses by BaseInlineFormSet.__init__
if len(initial):
formset = dynamic_formset_factory(formset, fk_initial)
yield formset, inline
def add_view(self, request, form_url='', extra_context=None):
context = {'dynamic_choices_binder': self.get_dynamic_choices_binder(request)}
context.update(extra_context or {})
return super(cls, self).add_view(request, form_url='', extra_context=context)
def change_view(self, request, object_id, extra_context=None):
context = {'dynamic_choices_binder': self.get_dynamic_choices_binder(request)}
context.update(extra_context or {})
return super(cls, self).change_view(request, object_id, extra_context=context)
return cls
0
Example 93
Project: ganetimgr Source File: instances.py
@login_required
def user_index_json(request):
cluster_slug = request.GET.get('cluster', None)
if request.user.is_anonymous():
action = {
'error': _(
"Permissions' violation. This action has been logged"
" and our admins will be notified about it"
)
}
return HttpResponse(json.dumps(action), mimetype='application/json')
p = Pool(20)
instances = []
bad_clusters = []
bad_instances = []
locked_clusters = []
locked_nodes = []
def _get_instances(cluster):
try:
cluster_locked_nodes = cluster.locked_nodes_from_nodegroup()
if cluster_locked_nodes:
locked_clusters.append(str(cluster.description))
locked_nodes.extend(cluster_locked_node_groups)
instances.extend(cluster.get_user_instances(request.user))
except GanetiApiError as e:
bad_clusters.append((cluster, format_ganeti_api_error(e)))
except Exception as e:
bad_clusters.append((cluster, e))
finally:
close_connection()
jresp = {}
cache_key = "user:%s:index:instances" % request.user.username
if cluster_slug:
cache_key = "user:%s:%s:instances" % (
request.user.username,
cluster_slug
)
res = cache.get(cache_key)
instancedetails = []
j = Pool(80)
locked_instances = cache.get('locked_instances')
def _get_instance_details(instance):
try:
if (
locked_instances is not None and
instance.name in locked_instances
):
instance.joblock = locked_instances['%s' % instance.name]
else:
instance.joblock = False
instancedetails.extend(generate_json(instance, request.user, locked_nodes))
except GanetiApiError as e:
bad_clusters.append((cluster, format_ganeti_api_error(e)))
except Exception as e:
bad_clusters.append((cluster, e))
finally:
close_connection()
if res is None:
if not request.user.is_anonymous():
if cluster_slug:
clusters = Cluster.objects.filter(slug=cluster_slug)
else:
# get only enabled clusters
clusters = Cluster.objects.filter(disabled=False)
p.map(_get_instances, clusters)
cache_timeout = 900
if bad_clusters:
if request.user.is_superuser:
djmessages.add_message(
request,
msgs.WARNING,
"Some instances may be missing because the"
" following clusters are unreachable: %s"
% (
", ".join(
[
"%s: %s" % (
c[0].slug or c[0].hostname,
c[1]
) for c in bad_clusters
]
)
)
)
else:
djmessages.add_message(
request,
msgs.WARNING,
"Some instances may be missing because the"
" following clusters are unreachable: %s"
% (
", ".join(
[c[0].description or c[0].hostname for c in bad_clusters]
)
)
)
pass
cache_timeout = 30
j.map(_get_instance_details, instances)
if locked_clusters:
djmessages.add_message(
request,
msgs.WARNING,
'Some clusters are under maintenance: <br> %s' % ', '.join(locked_clusters)
)
if bad_instances:
djmessages.add_message(
request,
msgs.WARNING,
"Could not get details for %s instances: %s. Please try again later." % (
str(len(bad_instances)),
', '.join([i.name for i in bad_instances])
)
)
cache_timeout = 30
jresp['aaData'] = instancedetails
cache.set(cache_key, jresp, cache_timeout)
res = jresp
return HttpResponse(json.dumps(res), mimetype='application/json')
0
Example 94
@staff_member_required
@csrf_exempt
def report(request):
outerkeyfunc = itemgetter('content_type_id')
content_types_list = []
if request.method == 'POST':
ignore_link_id = request.GET.get('ignore', None)
if ignore_link_id is not None:
link = Link.objects.get(id=ignore_link_id)
link.ignore = True
link.save()
if request.is_ajax():
json_data = json.dumps({'link': ignore_link_id})
return HttpResponse(json_data, content_type='application/javascript')
unignore_link_id = request.GET.get('unignore', None)
if unignore_link_id is not None:
link = Link.objects.get(id=unignore_link_id)
link.ignore = False
link.save()
if request.is_ajax():
json_data = json.dumps({'link': unignore_link_id})
return HttpResponse(json_data, content_type='application/javascript')
recheck_link_id = request.GET.get('recheck', None)
if recheck_link_id is not None:
link = Link.objects.get(id=recheck_link_id)
url = link.url
url.check_url(external_recheck_interval=0)
links = [x[0] for x in url.links.values_list('id')]
if request.is_ajax():
json_data = json.dumps({
'links': links,
'message': url.message,
'colour': url.colour,
})
return HttpResponse(json_data, content_type='application/javascript')
link_filter = request.GET.get('filters', 'show_invalid')
if link_filter == 'show_valid':
qset = Link.objects.filter(ignore=False, url__status__exact=True)
report_type = 'Good Links'
elif link_filter == 'show_unchecked':
qset = Link.objects.filter(ignore=False, url__last_checked__exact=None)
report_type = 'Untested Links'
elif link_filter == 'ignored':
qset = Link.objects.filter(ignore=True)
report_type = 'Ignored Links'
else:
qset = Link.objects.filter(ignore=False, url__status__exact=False)
report_type = 'Broken Links'
paginated_links = Paginator(qset, RESULTS_PER_PAGE, 0, True)
try:
page = int(request.GET.get('page', '1'))
except:
page = 0
# offset = (page - 1) * RESULTS_PER_PAGE
links = paginated_links.page(page)
# This code groups links into nested lists by content type and object id
# It's a bit nasty but we can't use groupby unless be get values()
# instead of a queryset because of the 'Object is not subscriptable' error
t = sorted(links.object_list.values(), key=outerkeyfunc)
for tk, tg in groupby(t, outerkeyfunc):
innerkeyfunc = itemgetter('object_id')
objects = []
tg = sorted(tg, key=innerkeyfunc)
for ok, og in groupby(tg, innerkeyfunc):
content_type = ContentType.objects.get(pk=tk)
og = list(og)
try:
object = None
if content_type.model_class():
object = content_type.model_class().objects.get(pk=ok)
except ObjectDoesNotExist:
pass
try:
admin_url = object.get_admin_url() # TODO allow method name to be configurable
except AttributeError:
try:
admin_url = reverse('admin:%s_%s_change' % (content_type.app_label, content_type.model), args=[ok])
except NoReverseMatch:
admin_url = None
objects.append({
'object': object,
'link_list': Link.objects.in_bulk([x['id'] for x in og]).values(), # Convert values_list back to queryset. Do we need to get values() or do we just need a list of ids?
'admin_url': admin_url,
})
content_types_list.append({
'content_type': content_type,
'object_list': objects
})
# Pass any querystring data back to the form minus page
rqst = request.GET.copy()
if 'page' in rqst:
del rqst['page']
return render(request, 'linkcheck/report.html', {
'content_types_list': content_types_list,
'pages': links,
'filter': link_filter,
'media': forms.Media(js=[static(get_jquery_min_js())]),
'qry_data': rqst.urlencode(),
'report_type': report_type,
'ignored_count': Link.objects.filter(ignore=True).count(),
},
)
0
Example 95
def condition(etag_func=None, last_modified_func=None):
"""
Decorator to support conditional retrieval (or change) for a view
function.
The parameters are callables to compute the ETag and last modified time for
the requested resource, respectively. The callables are passed the same
parameters as the view itself. The Etag function should return a string (or
None if the resource doesn't exist), whilst the last_modified function
should return a datetime object (or None if the resource doesn't exist).
If both parameters are provided, all the preconditions must be met before
the view is processed.
This decorator will either pass control to the wrapped view function or
return an HTTP 304 response (unmodified) or 412 response (preconditions
failed), depending upon the request method.
Any behavior marked as "undefined" in the HTTP spec (e.g. If-none-match
plus If-modified-since headers) will result in the view function being
called.
"""
def decorator(func):
@wraps(func, assigned=available_attrs(func))
def inner(request, *args, **kwargs):
# Get HTTP request headers
if_modified_since = request.META.get("HTTP_IF_MODIFIED_SINCE") 时间
if if_modified_since:
if_modified_since = parse_http_date_safe(if_modified_since)
if_none_match = request.META.get("HTTP_IF_NONE_MATCH")
if_match = request.META.get("HTTP_IF_MATCH")
if if_none_match or if_match:
# There can be more than one ETag in the request, so we
# consider the list of values.
try:
etags = parse_etags(if_none_match or if_match) 将所有的 hash 抽取出来
except ValueError:
# In case of invalid etag ignore all ETag headers.
# Apparently Opera sends invalidly quoted headers at times
# (we should be returning a 400 response, but that's a
# little extreme) -- this is Django bug #10681.
if_none_match = None
if_match = None
# Compute values (if any) for the requested resource.
if etag_func:
res_etag = etag_func(request, *args, **kwargs)
else:
res_etag = None
if last_modified_func:
dt = last_modified_func(request, *args, **kwargs)
if dt:
res_last_modified = timegm(dt.utctimetuple())
else:
res_last_modified = None
else:
res_last_modified = None
response = None
if not ((if_match and (if_modified_since or if_none_match)) or
(if_match and if_none_match)):
# We only get here if no undefined combinations of headers are
# specified.
if ((if_none_match and (res_etag in etags or
"*" in etags and res_etag)) and
(not if_modified_since or
(res_last_modified and if_modified_since and
res_last_modified <= if_modified_since))): 文件最后修改时间稍早
if request.method in ("GET", "HEAD"):
response = HttpResponseNotModified() 资源没有改变
else:
logger.warning('Precondition Failed: %s', request.path,
extra={
'status_code': 412,
'request': request
}
)
response = HttpResponse(status=412)
elif if_match and ((not res_etag and "*" in etags) or
(res_etag and res_etag not in etags)):
logger.warning('Precondition Failed: %s', request.path,
extra={
'status_code': 412,
'request': request
}
)
response = HttpResponse(status=412)
elif (not if_none_match and request.method == "GET" and
res_last_modified and if_modified_since and
res_last_modified <= if_modified_since):
response = HttpResponseNotModified()
if response is None:
response = func(request, *args, **kwargs) 这里调用被修饰的函数
# Set relevant headers on the response if they don't already exist.
if res_last_modified and not response.has_header('Last-Modified'): 如果没有 Last-Modified 字段, 便添加
response['Last-Modified'] = http_date(res_last_modified)
if res_etag and not response.has_header('ETag'):
response['ETag'] = quote_etag(res_etag)
return response
0
Example 96
Project: movieduk Source File: views.py
@csrf_exempt
def get_search_list(request, option = "file"):
if request.is_ajax() and request.method == "POST":
try:
username = request.session['DukUser']
user = DukUser.objects.get(username = username)
ui = user.usermovie_set.all()[0]
except:
user = None
query = request.POST.get('query')
#print query
option = request.POST.get('option')
#print option
count = int(request.POST.get('count', '10'))
page = int(request.POST.get('page', '0'))
M = Movie.objects.all().exclude(year='xxxx')
if option == 'title':
movies = M.filter(title1__contains=query).order_by('-rank','-year')
elif option == 'year':
movies = M.filter(year=query).order_by('-rank','-year')
elif option == 'genre':
movies = M.filter(genre=query).order_by('-rank','-year')
elif option == 'country':
movies = M.filter(country=query).order_by('-rank','-year')
elif option == 'file':
movies = Movie.objects.filter(video__gte=1).distinct().order_by('-rank','-year')
else:
movies = []
if option != 'file':
movies = movies.order_by('-rank','-year')[page * count:page * count + count]
movie_json = {}
if count > len(movies):
movie_json['end'] = True
if len(movies) == 0:
return 'fail'
f = open(settings.TEMPLATE_DIRS[0] + '/core/movie_item.html','r')
r = f.read()
t = Template(r)
for m in movies:
m.like_count = len(DukUser.objects.filter(usermovie__liked = m))
m.dislike_count = len(DukUser.objects.filter(usermovie__disliked = m))
if user:
if m in ui.liked.all():
m.like= True
else:
m.like = False
if m in ui.disliked.all():
m.dislike = True
else:
m.dislike = False
m.director_list = m.directors.all()
m.main_list = m.main.all()
if m.poster_url != '':
url = m.poster_url
new_url = url[url.rfind('naver.net') + 9:]
m.poster = m.year + '/' + m.country_code + '/' + 'pic_' + md5(new_url).hexdigest() + '.jpg'
else:
m.poster = ''
if m.poster_url == '':
m.poster_url = False
context = {'MEDIA_URL': MEDIA_URL, 'movies' : movies}
html = t.render(Context(context))
movie_json['source'] = html
results = []
results.append(movie_json)
data = json.dumps(results)
else:
data = "fail"
mimetype = 'application/json'
return HttpResponse(data, mimetype)
0
Example 97
def condition(etag_func=None, last_modified_func=None):
"""
Decorator to support conditional retrieval (or change) for a view
function.
The parameters are callables to compute the ETag and last modified time for
the requested resource, respectively. The callables are passed the same
parameters as the view itself. The Etag function should return a string (or
None if the resource doesn't exist), whilst the last_modified function
should return a datetime object (or None if the resource doesn't exist).
If both parameters are provided, all the preconditions must be met before
the view is processed.
This decorator will either pass control to the wrapped view function or
return an HTTP 304 response (unmodified) or 412 response (preconditions
failed), depending upon the request method.
Any behavior marked as "undefined" in the HTTP spec (e.g. If-none-match
plus If-modified-since headers) will result in the view function being
called.
"""
def decorator(func):
def inner(request, *args, **kwargs):
# Get HTTP request headers
if_modified_since = request.META.get("HTTP_IF_MODIFIED_SINCE")
if if_modified_since:
if_modified_since = parse_http_date_safe(if_modified_since)
if_none_match = request.META.get("HTTP_IF_NONE_MATCH")
if_match = request.META.get("HTTP_IF_MATCH")
if if_none_match or if_match:
# There can be more than one ETag in the request, so we
# consider the list of values.
try:
etags = parse_etags(if_none_match or if_match)
except ValueError:
# In case of invalid etag ignore all ETag headers.
# Apparently Opera sends invalidly quoted headers at times
# (we should be returning a 400 response, but that's a
# little extreme) -- this is Django bug #10681.
if_none_match = None
if_match = None
# Compute values (if any) for the requested resource.
if etag_func:
res_etag = etag_func(request, *args, **kwargs)
else:
res_etag = None
if last_modified_func:
dt = last_modified_func(request, *args, **kwargs)
if dt:
res_last_modified = timegm(dt.utctimetuple())
else:
res_last_modified = None
else:
res_last_modified = None
response = None
if not ((if_match and (if_modified_since or if_none_match)) or
(if_match and if_none_match)):
# We only get here if no undefined combinations of headers are
# specified.
if ((if_none_match and (res_etag in etags or
"*" in etags and res_etag)) and
(not if_modified_since or
(res_last_modified and if_modified_since and
res_last_modified <= if_modified_since))):
if request.method in ("GET", "HEAD"):
response = HttpResponseNotModified()
else:
logger.warning('Precondition Failed: %s' % request.path,
extra={
'status_code': 412,
'request': request
}
)
response = HttpResponse(status=412)
elif if_match and ((not res_etag and "*" in etags) or
(res_etag and res_etag not in etags)):
logger.warning('Precondition Failed: %s' % request.path,
extra={
'status_code': 412,
'request': request
}
)
response = HttpResponse(status=412)
elif (not if_none_match and request.method == "GET" and
res_last_modified and if_modified_since and
res_last_modified <= if_modified_since):
response = HttpResponseNotModified()
if response is None:
response = func(request, *args, **kwargs)
# Set relevant headers on the response if they don't already exist.
if res_last_modified and not response.has_header('Last-Modified'):
response['Last-Modified'] = http_date(res_last_modified)
if res_etag and not response.has_header('ETag'):
response['ETag'] = quote_etag(res_etag)
return response
return inner
return decorator
0
Example 98
Project: inthe.am Source File: task.py
@csrf_exempt
def incoming_sms(request, username):
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
return HttpResponse(status=404)
r = TwilioResponse()
# This request is unauthenticated; we'll need to fetch the user's
# store directly rather than looking it up via the auth cookie.
store = models.TaskStore.get_for_user(user)
if not store.twilio_auth_token:
log_args = (
"Incoming SMS for %s, but no auth token specified.",
user,
user,
)
logger.warning(*log_args)
store.log_error(*log_args)
return HttpResponse(status=404)
if store.sms_whitelist:
incoming_number = re.sub('[^0-9]', '', request.POST['From'])
valid_numbers = [
re.sub('[^0-9]', '', n)
for n in store.sms_whitelist.split('\n')
]
if incoming_number not in valid_numbers:
log_args = (
"Incoming SMS for %s, but phone number %s is not "
"in the whitelist.",
user,
incoming_number,
)
store.log_error(*log_args)
logger.warning(
*log_args,
extra={
'data': {
'incoming_number': incoming_number,
'whitelist': valid_numbers,
}
}
)
return HttpResponseForbidden()
try:
validator = RequestValidator(store.twilio_auth_token)
url = request.build_absolute_uri()
signature = request.META['HTTP_X_TWILIO_SIGNATURE']
except (AttributeError, KeyError) as e:
log_args = (
"Incoming SMS for %s, but error encountered while "
"attempting to build request validator: %s.",
user,
e,
)
logger.exception(*log_args)
store.log_error(*log_args)
return HttpResponseForbidden()
if not validator.validate(url, request.POST, signature):
log_args = (
"Incoming SMS for %s, but validator rejected message.",
user,
)
logger.warning(*log_args)
store.log_error(*log_args)
return HttpResponseForbidden()
with git_checkpoint(store, "Incoming SMS", sync=True):
from_ = request.POST['From']
body = request.POST['Body']
task_info = body[4:]
if not body.lower().startswith('add'):
if store.sms_replies >= store.REPLY_ERROR:
r.sms("Bad Request: Unknown command.")
log_args = (
"Incoming SMS from %s had no recognized command: '%s'." % (
from_,
body,
),
)
logger.warning(*log_args)
store.log_error(*log_args)
elif not task_info:
log_args = (
"Incoming SMS from %s had no content." % (
from_,
body,
),
)
logger.warning(*log_args)
store.log_error(*log_args)
if store.sms_replies >= store.REPLY_ERROR:
r.sms("Bad Request: Empty task.")
else:
task_uuid = str(uuid.uuid4())
task_args = (
['add'] +
shlex_without_quotes(store.sms_arguments) +
shlex_without_quotes(task_info)
)
task_args.append('uuid:%s' % task_uuid)
result = store.client._execute_safe(*task_args)
stdout, stderr = result
if store.sms_replies >= store.REPLY_ALL:
r.sms("Added.")
log_args = (
"Added task %s via SMS from %s; message '%s'; "
"automatic args: '%s';"
"response: '%s'." % (
task_uuid,
from_,
body,
store.sms_arguments,
stdout,
),
)
logger.info(*log_args)
store.log_message(*log_args)
return HttpResponse(str(r), content_type='application/xml')
0
Example 99
Project: django-lfs Source File: variants.py
@permission_required("core.manage_shop")
def manage_variants(request, product_id, as_string=False, variant_simple_form=None, template_name="manage/product/variants.html"):
"""Manages the variants of a product.
"""
product = Product.objects.get(pk=product_id)
all_properties = product.get_variants_properties()
property_form = PropertyForm()
property_option_form = PropertyOptionForm()
if not variant_simple_form:
variant_simple_form = ProductVariantSimpleForm(all_properties=all_properties)
display_type_form = DisplayTypeForm(instance=product)
default_variant_form = DefaultVariantForm(instance=product)
category_variant_form = CategoryVariantForm(instance=product)
pid = product.get_parent().pk
properties_version = get_cache_group_id('global-properties-version')
group_id = '%s-%s' % (properties_version, get_cache_group_id('properties-%s' % pid))
cache_key = "%s-manage-properties-variants-%s-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, group_id, product_id)
variants = cache.get(cache_key)
# Get all properties. We need to traverse through all property / options
# in order to select the options of the current variant.
if variants is None:
variants = []
props_dicts = product.get_variants_properties()
# for each property prepare list of its options
all_props = [prop_dict['property'] for prop_dict in props_dicts]
props_options = {}
for o in PropertyOption.objects.filter(property__in=all_props):
props_options.setdefault(o.property_id, {})
props_options[o.property_id][str(o.pk)] = {
"id": o.pk,
"name": o.name,
"selected": False
}
product_variants = product.variants.all().order_by("variant_position")
selected_options = {}
for prop_dict in props_dicts:
prop = prop_dict['property']
property_group = prop_dict['property_group']
property_group_id = property_group.pk if property_group else 0
for so in ProductPropertyValue.objects.filter(property=prop,
property_group=property_group,
product__in=product_variants,
type=PROPERTY_VALUE_TYPE_VARIANT):
ppk = so.product_id
selected_groups = selected_options.setdefault(ppk, {})
selected_groups.setdefault(property_group_id, {})[so.property_id] = so.value
for variant in product_variants:
properties = []
for prop_dict in props_dicts:
prop = prop_dict['property']
property_group = prop_dict['property_group']
property_group_id = property_group.pk if property_group else 0
options = deepcopy(props_options.get(prop.pk, {}))
try:
sop = selected_options[variant.pk][property_group_id][prop.pk]
options[sop]['selected'] = True
except KeyError:
pass
properties.append({
"id": prop.pk,
"name": prop.name,
"options": options.values(),
"property_group_id": property_group.pk if property_group else 0,
"property_group": property_group
})
variants.append({
"id": variant.id,
"active": variant.active,
"slug": variant.slug,
"sku": variant.sku,
"name": variant.name,
"price": variant.price,
"active_price": variant.active_price,
"active_sku": variant.active_sku,
"active_name": variant.active_name,
"position": variant.variant_position,
"properties": properties
})
cache.set(cache_key, variants)
# Generate list of all property groups; used for group selection
product_property_group_ids = [p.id for p in product.property_groups.all()]
shop_property_groups = []
for property_group in PropertyGroup.objects.all():
shop_property_groups.append({
"id": property_group.id,
"name": property_group.name,
"selected": property_group.id in product_property_group_ids,
})
result = render_to_string(template_name, RequestContext(request, {
"product": product,
"variants": variants,
"shop_property_groups": shop_property_groups,
"local_properties": product.get_local_properties(),
"all_properties": all_properties,
"property_option_form": property_option_form,
"property_form": property_form,
"variant_simple_form": variant_simple_form,
"display_type_form": display_type_form,
"default_variant_form": default_variant_form,
"category_variant_form": category_variant_form,
}))
if as_string:
return result
else:
return HttpResponse(result)
0
Example 100
def post(self, request):
"""Process a CyberSource merchant notification and place an order for paid products as appropriate."""
# Note (CCB): Orders should not be created until the payment processor has validated the response's signature.
# This validation is performed in the handle_payment method. After that method succeeds, the response can be
# safely assumed to have originated from CyberSource.
cybersource_response = request.POST.dict()
basket = None
transaction_id = None
try:
transaction_id = cybersource_response.get('transaction_id')
order_number = cybersource_response.get('req_reference_number')
basket_id = OrderNumberGenerator().basket_id(order_number)
logger.info(
'Received CyberSource merchant notification for transaction [%s], associated with basket [%d].',
transaction_id,
basket_id
)
basket = self._get_basket(basket_id)
if not basket:
logger.error('Received payment for non-existent basket [%s].', basket_id)
return HttpResponse(status=400)
finally:
# Store the response in the database regardless of its authenticity.
ppr = self.payment_processor.record_processor_response(cybersource_response, transaction_id=transaction_id,
basket=basket)
try:
# Explicitly delimit operations which will be rolled back if an exception occurs.
with transaction.atomic():
try:
self.handle_payment(cybersource_response, basket)
except InvalidSignatureError:
logger.exception(
'Received an invalid CyberSource response. The payment response was recorded in entry [%d].',
ppr.id
)
return HttpResponse(status=400)
except (UserCancelled, TransactionDeclined) as exception:
logger.info(
'CyberSource payment did not complete for basket [%d] because [%s]. '
'The payment response was recorded in entry [%d].',
basket.id,
exception.__class__.__name__,
ppr.id
)
return HttpResponse()
except PaymentError:
logger.exception(
'CyberSource payment failed for basket [%d]. The payment response was recorded in entry [%d].',
basket.id,
ppr.id
)
return HttpResponse()
except: # pylint: disable=bare-except
logger.exception('Attempts to handle payment for basket [%d] failed.', basket.id)
return HttpResponse(status=500)
try:
# Note (CCB): In the future, if we do end up shipping physical products, we will need to
# properly implement shipping methods. For more, see
# http://django-oscar.readthedocs.org/en/latest/howto/how_to_configure_shipping.html.
shipping_method = NoShippingRequired()
shipping_charge = shipping_method.calculate(basket)
# Note (CCB): This calculation assumes the payment processor has not sent a partial authorization,
# thus we use the amounts stored in the database rather than those received from the payment processor.
order_total = OrderTotalCalculator().calculate(basket, shipping_charge)
billing_address = self._get_billing_address(cybersource_response)
user = basket.owner
self.handle_order_placement(
order_number,
user,
basket,
None,
shipping_method,
shipping_charge,
billing_address,
order_total,
request=request
)
return HttpResponse()
except: # pylint: disable=bare-except
logger.exception(self.order_placement_failure_msg, basket.id)
return HttpResponse(status=500)