django.http.HttpResponseBadRequest

Here are the examples of the python api django.http.HttpResponseBadRequest taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 51

Project: django-push
Source File: views.py
View license
    def get(self, request, pk, *args, **kwargs):
        subscription = get_object_or_404(Subscription, pk=pk)
        params = ['hub.mode', 'hub.topic', 'hub.challenge']
        missing = [p for p in params if p not in request.GET]
        if missing:
            return HttpResponseBadRequest("Missing parameters: {0}".format(
                ", ".join(missing)))

        topic = request.GET['hub.topic']
        if not topic == subscription.topic:
            return HttpResponseBadRequest("Mismatching topic URL")

        mode = request.GET['hub.mode']

        if mode not in ['subscribe', 'unsubscribe', 'denied']:
            return HttpResponseBadRequest("Unrecognized hub.mode parameter")

        if mode == 'subscribe':
            if 'hub.lease_seconds' not in request.GET:
                return HttpResponseBadRequest(
                    "Missing hub.lease_seconds parameter")

            if not request.GET['hub.lease_seconds'].isdigit():
                return HttpResponseBadRequest(
                    "hub.lease_seconds must be an integer")

            seconds = int(request.GET['hub.lease_seconds'])
            subscription.set_expiration(seconds)
            subscription.verified = True
            logger.debug("Verifying subscription for topic {0} via {1} "
                         "(expires in {2}s)".format(subscription.topic,
                                                    subscription.hub,
                                                    seconds))
            Subscription.objects.filter(pk=subscription.pk).update(
                verified=True,
                lease_expiration=subscription.lease_expiration)

        if mode == 'unsubscribe':
            # TODO make sure it was pending deletion
            logger.debug("Deleting subscription for topic {0} via {1}".format(
                subscription.topic, subscription.hub))
            subscription.delete()

        # TODO handle denied subscriptions

        return HttpResponse(request.GET['hub.challenge'])

Example 52

Project: canvas
Source File: views.py
View license
def sql_profile(request):
    """
    Returns the output of running the SQL and getting the profiling statistics.

    Expected GET variables:
        sql: urlencoded sql with positional arguments
        params: JSON encoded parameter values
        duration: time for SQL to execute passed in from toolbar just for redisplay
        hash: the hash of (secret + sql + params) for tamper checking
    """
    from debug_toolbar.panels.sql import reformat_sql
    sql = request.GET.get('sql', '')
    params = request.GET.get('params', '')
    hash = sha_constructor(settings.SECRET_KEY + sql + params).hexdigest()
    if hash != request.GET.get('hash', ''):
        return HttpResponseBadRequest('Tamper alert') # SQL Tampering alert
    if sql.lower().strip().startswith('select'):
        params = simplejson.loads(params)
        cursor = connection.cursor()
        result = None
        headers = None
        result_error = None
        try:
            cursor.execute("SET PROFILING=1") # Enable profiling
            cursor.execute(sql, params) # Execute SELECT
            cursor.execute("SET PROFILING=0") # Disable profiling
            # The Query ID should always be 1 here but I'll subselect to get the last one just in case...
            cursor.execute("SELECT * FROM information_schema.profiling WHERE query_id=(SELECT query_id FROM information_schema.profiling ORDER BY query_id DESC LIMIT 1)")
            headers = [d[0] for d in cursor.description]
            result = cursor.fetchall()
        except:
            result_error = "Profiling is either not available or not supported by your database."
        cursor.close()
        context = {
            'result': result,
            'result_error': result_error,
            'sql': reformat_sql(cursor.db.ops.last_executed_query(cursor, sql, params)),
            'duration': request.GET.get('duration', 0.0),
            'headers': headers,
        }
        return render_to_response('debug_toolbar/panels/sql_profile.html', context)
    raise InvalidSQLError("Only 'select' queries are allowed.")

Example 53

Project: canvas
Source File: views.py
View license
def template_source(request):
    """
    Return the source of a template, syntax-highlighted by Pygments if
    it's available.
    """
    from django.template import TemplateDoesNotExist
    from django.utils.safestring import mark_safe
    from django.conf import settings

    template_name = request.GET.get('template', None)
    if template_name is None:
        return HttpResponseBadRequest('"template" key is required')

    try: # Django 1.2 ...
        from django.template.loader import find_template_loader, make_origin
        loaders = []
        for loader_name in settings.TEMPLATE_LOADERS:
            loader = find_template_loader(loader_name)
            if loader is not None:
                loaders.append(loader)
        for loader in loaders:
            try:
                source, display_name = loader.load_template_source(template_name)
                origin = make_origin(display_name, loader, template_name, settings.TEMPLATE_DIRS)
                break
            except TemplateDoesNotExist:
                source = "Template Does Not Exist: %s" % (template_name,)
    except (ImportError, AttributeError): # Django 1.1 ...
        from django.template.loader import find_template_source
        source, origin = find_template_source(template_name)

    try:
        from pygments import highlight
        from pygments.lexers import HtmlDjangoLexer
        from pygments.formatters import HtmlFormatter

        source = highlight(source, HtmlDjangoLexer(), HtmlFormatter())
        source = mark_safe(source)
        source.pygmentized = True
    except ImportError:
        pass

    return render_to_response('debug_toolbar/panels/template_source.html', {
        'source': source,
        'template_name': template_name
    })

Example 54

Project: django-dynamic-choices
Source File: admin.py
View license
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

Example 55

Project: indivo_server
Source File: view_decorators.py
View license
def marsloader(query_api_support = False):
  def marsloader_decorator(func):
    def marsloader_func(request, *args, **kwargs):
      """MARS_loader (Modifying Arguments for the Result Set) 
      
      adds arguments specifically meant to modify the result set 
      (eg. limit, offset and order_by)

      04-05-2011: Modified to Handle the New Query Interface
      New arguments are: group_by, aggregate_by, date_group,
      date_range, generic report_specific_filters.
      
      Also: No longer checks that the URL ends in a '/'. We assume
      that if you didn't want to call this function, you wouldn't
      have decorated the view with it.
      """
      
      def parse_string(value):
          return value
      
      def parse_int(value):
          return int(value)
      
      def parse_status(value):
          return models.StatusName.objects.get(name=value)
      
      def parse_aggregate_by(value):
          operator, field = value.split('*')
          field = None if field == '' else field
          return {'operator':operator, 'field':field}
      
      def parse_date_range(value):
          field, start_date, end_date = value.split('*')
          start_date = None if start_date == '' else iso8601.parse_utc_date(start_date)
          end_date = None if end_date == '' else iso8601.parse_utc_date(end_date)
          return {'field':field, 'start_date':start_date, 'end_date':end_date}
      
      def parse_date_group(value):
          field, time_incr = value.split('*')
          return {'field':field, 'time_incr':time_incr}
      
      check_safety()
      
      parse_map = {
        'limit': parse_int,
        'offset': parse_int,
        'order_by': parse_string,
        'status': parse_status,
        'group_by': parse_string,
        'aggregate_by': parse_aggregate_by,  
        'date_range': parse_date_range,   
        'date_group': parse_date_group,            
      }
      
      ignore_map = {
        'response_format': True              
      }
      
      # This should be abstracted
      # StatusName 'active' should always be available
      arg_defaults = {
        'limit': 100, 
        'offset': 0,
        'order_by': '-%s'%(DEFAULT_ORDERBY) if not request.GET.has_key('aggregate_by') or not query_api_support else None,
        'status': models.StatusName.objects.get(name='active'),
        }
      query_api_defaults = {
        'group_by': None,
        'aggregate_by': None,
        'date_range': None,
        'date_group': None,
        }
     
      base_options = {}
      report_specific_filters = {}
      
      # set defaults
      base_options.update(arg_defaults)
      if query_api_support:
          base_options.update(query_api_defaults)
          base_options['filters'] = report_specific_filters
      
      for _arg, value in request.GET.iteritems():
        arg = str(_arg)
        try:
          if parse_map.has_key(arg):
              base_options[arg] = parse_map[arg](value)
          elif ignore_map.has_key(arg):
              pass
          else:
              # might be field-specific query parameter, allow individual reports to type-check
              report_specific_filters[arg] = value
        except models.StatusName.DoesNotExist:
          raise Http404
        except ValueError:
          return HttpResponseBadRequest('Argument %s must be formatted according to the Indivo Query API'%(arg))

      # Check that the new query_options argument is in func()
      if len(inspect.getargspec(func)) > 0:
        if QUERY_OPTIONS_ARG not in inspect.getargspec(func)[0]:
          raise Exception("Missing arg " + QUERY_OPTIONS_ARG + " in " + func.func_name)
      
      # update args
      kwargs[QUERY_OPTIONS_ARG] = base_options
      
      # call the view
      return func(request, **kwargs)

    # Return the wrapped Function
    return functools.update_wrapper(marsloader_func, func)

  # Return the function decorator
  return marsloader_decorator

Example 56

Project: indivo_server
Source File: account.py
View license
@transaction.commit_manually
def account_authsystem_add(request, account):
    """ Add a new method of authentication to an account.

    Accounts cannot be logged into unless there exists a
    mechanism for authenticating them. Indivo supports one
    built-in mechanism, password auth, but is extensible with
    other mechanisms (i.e., LDAP, etc.). If an external mechanism 
    is used, a UI app is responsible for user authentication, and 
    this call merely registers with indivo server the fact that 
    the UI can handle auth. If password auth is used, this call 
    additionally registers the password with indivo server.
    Thus, this call can be used to add internal or external auth 
    systems.

    request.POST must contain:

    * *system*: The identifier (a short slug) associated with the
      desired auth system. ``password`` identifies the internal
      password system, and external auth systems will define their
      own identifiers.

    * *username*: The username that this account will use to 
      authenticate against the new authsystem
      
    * *password*: The password to pair with the username.
      **ONLY REQUIRED IF THE AUTH SYSTEM IS THE INTERNAL
      PASSWORD SYSTEM**.

    Will return :http:statuscode:`200` on success, 
    :http:statuscode:`403` if the indicated auth system doesn't exist,
    and :http:statuscode:`400` if the POST data didn't contain a system
    and a username (and a password if system was ``password``), or if
    the account is already registered for the given authsystem, or a 
    different account is already registered for the given authsystem with
    the same username.

    """
    
    # check for username
    USERNAME, PASSWORD = 'username', 'password'
    
    if request.POST.has_key(USERNAME):
        username = request.POST[USERNAME]
    else:
        transaction.rollback()
        return HttpResponseBadRequest('No username')
    
    # did we get a system?
    desired_system = request.POST.get('system')
    if not desired_system:
        transaction.rollback()
        return HttpResponseBadRequest('No system')
    
    # if we got "password" as system, did we get a password?
    new_password = None
    if 'password' == desired_system:
        new_password = request.POST.get(PASSWORD)
        if not new_password:
            transaction.rollback()
            return HttpResponseBadRequest('No password')
    
    # set the auth system
    try:
        system = AuthSystem.objects.get(short_name = desired_system)
        account.auth_systems.create(username = username, 
                                 auth_system = system)
    except AuthSystem.DoesNotExist:
        transaction.rollback()
        raise PermissionDenied()
    except IntegrityError:
        transaction.rollback()
        return HttpResponseBadRequest('Duplicate attempt to add authsystem to account')
    else:
        if system == AuthSystem.PASSWORD() and new_password:
            account.password_set(new_password)
            account.set_state(ACTIVE_STATE)
            account.save()
        
        transaction.commit()
        # return the account info instead
        return DONE

Example 57

Project: indivo_server
Source File: account.py
View license
@transaction.commit_on_success
def account_create(request):
    """ Create a new account, and send out initialization emails.
    
    ``request.POST`` holds the creation arguments. 

    In Demo Mode, this call
    automatically creates new records for the account, populated with
    sample data. See :doc:`/sample-data` for details.
    
    Required Parameters:
    
    * *account_id*: an identifier for the new address. Must be formatted
      as an email address.
    
    Optional Parameters:
    
    * *full_name*: The full name to associate with the account. Defaults
      to the empty string.
    
    * *contact_email*: A valid email at which the account holder can 
      be reached. Defaults to the *account_id* parameter.
    
    * *primary_secret_p*: ``0`` or ``1``. Whether or not to associate 
      a primary secret with the account. Defaults to ``1``.
    
    * *secondary_secret_p*: ``0`` or ``1``. Whether or not to associate
      a secondary secret with the account. Defaults to ``0``.
    
    After creating the new account, this call generates secrets for it,
    and then emails the user (at *contact_email*) with their activation
    link, which contains the primary secret.
    
    This call will return :http:statuscode:`200` with info about the new
    account on success, :http:statuscode:`400` if *account_id* isn't 
    provided or isn't a valid email address, or if an account already
    exists with an id matching *account_id*.
      
    """
    
    account_id = request.POST.get('account_id', None)
    if not account_id or not utils.is_valid_email(account_id):
        return HttpResponseBadRequest("Account ID not valid")
    
    contact_email = request.POST.get('contact_email', account_id)
    if not contact_email or not utils.is_valid_email(contact_email):
        return HttpResponseBadRequest("Contact email not valid")
    
    new_account, create_p = Account.objects.get_or_create(email=urllib.unquote(account_id).lower().strip())
    if create_p:
        
        # generate a secondary secret or not? Requestor can say no.
        # trust model makes sense: the admin app requestor only decides whether or not 
        # they control the additional interaction or if it's not necessary. They never
        # see the primary secret.
        
        new_account.full_name = request.POST.get('full_name', '')
        new_account.contact_email = contact_email
        
        new_account.creator = request.principal
        
        password            = request.POST.get('password', None)
        primary_secret_p    = (request.POST.get('primary_secret_p', "1") == "1")
        secondary_secret_p  = (request.POST.get('secondary_secret_p', "0") == "1")
        
        # we don't allow setting the password here anymore
        new_account.save()
            
        if settings.DEMO_MODE:
            loader = IndivoDataLoader(request.principal)
            
            # Create new records for the account, populated by sample data.
            for record_label, data_profile in settings.DEMO_PROFILES.iteritems():
                
                # Create the record
                record = Record.objects.create(creator=request.principal,
                                               label=record_label,
                                               owner=new_account)

                try:
                    # Load the data: no transactions, as we're already managing them above
                    loader.load_profile(record, data_profile, transaction=False)
                except Exception, e: # Something went wrong: roll everything back and fail
                    logging.exception(e)
                    raise

        if primary_secret_p:
            new_account.generate_secrets(secondary_secret_p = secondary_secret_p)
            try:
                new_account.send_secret()
            except Exception, e:
                logging.exception(e)

                
    # account already existed
    else:
        return HttpResponseBadRequest("An account with email address %s already exists." % account_id)
    
    return render_template('account', {'account': new_account}, type='xml')

Example 58

View license
    def postfinance_ipn(self, request):
        """
        Similar to paypal's IPN, postfinance will send an instant notification to the website, 
        passing the following parameters in the URL:
        
        orderID=Test27&
        currency=CHF&
        amount=54&
        PM=CreditCard&
        ACCEPTANCE=test123&
        STATUS=9&
        CARDNO=XXXXXXXXXXXX3333&ED=0317&
        CN=Testauzore+Testos&
        TRXDATE=11/08/10&
        PAYID=8628366&
        NCERROR=0&
        BRAND=VISA&
        IPCTY=CH&
        CCCTY=US&
        ECI=7&
        CVCCheck=NO&
        AAVCheck=NO&
        VC=NO&
        IP=84.226.127.220&
        SHASIGN=CEE483B0557B8E3437A55094221E15C7DB6A0D63
        
        Cornfirms that payment has been completed and marks invoice as paid.
        This can come from two sources: Wither the client was redirected to our success page from postfinance (and so the order
        information is contained in GET parameters), or the client messed up and postfinance sends us a direct server-to-server
        http connection with parameters passed in the POST fields.
        
        """
        
        data = request.REQUEST
        # Verify that the info is valid (with the SHA sum)
        valid = security_check(data, settings.POSTFINANCE_SECRET_KEY)
        if valid:
            order_id = data['orderID']
            order = self.shop.get_order_for_id(order_id) # Get the order from either the POST or the GET parameters
            transaction_id = data['PAYID']
            amount = data['amount']
            # Create an IPN transaction trace in the database
            PostfinanceIPN.objects.create(
                orderID=order_id,
                currency=order.get('currency', ''),
                amount=order.get('amount', ''),
                PM=order.get('PM', ''),
                ACCEPTANCE=order.get('ACCEPTANCE', ''),
                STATUS=order.get('STATUS', ''),
                CARDNO=order.get('CARDNO', ''),
                CN=order.get('CN', ''),
                TRXDATE=order.get('TRXDATE', ''),
                PAYID=order.get('PAYID', ''),
                NCERROR=order.get('NCERROR', ''),
                BRAND=order.get('BRAND', ''),
                IPCTY=order.get('IPCTY', ''),
                CCCTY=order.get('CCCTY', ''),
                ECI=order.get('ECI', ''),
                CVCCheck=order.get('CVCCheck', ''),
                AAVCheck=order.get('AAVCheck', ''),
                VC=order.get('VC', ''),
                IP=order.get('IP', ''),
                SHASIGNorder =order.get('SHASIGNorder', ''),
            )
            # This actually records the payment in the shop's database
            self.shop.confirm_payment(order, amount, transaction_id, self.backend_name)
            
            return HttpResponse('OKAY')
            
        else: # Checksum failed
            return HttpResponseBadRequest()

Example 59

Project: django-nonrel
Source File: modpython.py
View license
    def __call__(self, req):
        warn(('The mod_python handler is deprecated; use a WSGI or FastCGI server instead.'),
             PendingDeprecationWarning)

        # mod_python fakes the environ, and thus doesn't process SetEnv.  This fixes that
        os.environ.update(req.subprocess_env)

        # now that the environ works we can see the correct settings, so imports
        # that use settings now can work
        from django.conf import settings

        # if we need to set up middleware, now that settings works we can do it now.
        if self._request_middleware is None:
            self.load_middleware()

        set_script_prefix(req.get_options().get('django.root', ''))
        signals.request_started.send(sender=self.__class__)
        try:
            try:
                request = self.request_class(req)
            except UnicodeDecodeError:
                logger.warning('Bad Request (UnicodeDecodeError): %s' % request.path,
                    exc_info=sys.exc_info(),
                    extra={
                        'status_code': 400,
                        'request': request
                    }
                )
                response = http.HttpResponseBadRequest()
            else:
                response = self.get_response(request)
        finally:
            signals.request_finished.send(sender=self.__class__)

        # Convert our custom HttpResponse object back into the mod_python req.
        req.content_type = response['Content-Type']
        for key, value in response.items():
            if key != 'content-type':
                req.headers_out[str(key)] = str(value)
        for c in response.cookies.values():
            req.headers_out.add('Set-Cookie', c.output(header=''))
        req.status = response.status_code
        try:
            for chunk in response:
                req.write(chunk)
        finally:
            response.close()

        return 0 # mod_python.apache.OK

Example 60

Project: django-bcp
Source File: views.py
View license
def generate(request, code, barcode_type='Standard39', auto_print=True):
    """
     Returns a PDF Barcode using ReportLab
    """

    from reportlab.graphics.shapes import String
    from reportlab.graphics import renderPDF
    from reportlab.graphics.barcode import createBarcodeDrawing
    from reportlab.pdfbase import pdfdoc
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont

    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'inline; filename=%s.pdf' % (code,)

    # Config
    import bcp.settings as bcp_settings
    font_size = bcp_settings.FONT_SIZE
    bar_height = bcp_settings.BAR_HEIGHT
    bar_width = bcp_settings.BAR_WIDTH
    font_name = bcp_settings.FONT_NAME
    font_path = bcp_settings.FONT_PATH
    try:
        # If this is extended to different barcode types, then these options will need to be specified differently, eg not all formats support checksum.
        bc = createBarcodeDrawing(barcode_type, barHeight=bar_height, barWidth=bar_width, value=str(code), isoScale=True, quiet=bcp_settings.BAR_QUIET, checksum=bcp_settings.BAR_CHECKSUM,)
    except KeyError, e:
        return HttpResponseBadRequest('Barcode Generation Failed: %s' % (e))

    # Register the font
    pdfmetrics.registerFont(TTFont(font_name, font_path))

    # Set JS to Autoprint document
    if auto_print:
        pdfdoc.PDFCatalog.OpenAction = '<</S/JavaScript/JS(this.print\({bUI:true,bSilent:false,bShrinkToFit:true}\);)>>'
        pdfdoc.PDFInfo.title = code # nicety :)

    # Position for our text label
    x = bc.width / 2
    y = - font_size  # or (bar_height + font_size) if placing on top
    # The textual barcode
    text = String(x, y, code, textAnchor='middle', fontName=font_name, fontSize=font_size)
    bc.add(text)
    bc = bc.resized() # resize barcode drawing object to accommodate text added

    buffer = StringIO() # buffer for the output
    renderPDF.drawToFile(bc, buffer, autoSize=1) # write PDF to buffer

    # Get the value of the StringIO buffer and write it to the response.
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)

    return response

Example 61

Project: ADL_LRS
Source File: views.py
View license
@login_required(login_url="/accounts/login")
def user_authorization(request, form_class=AuthorizeRequestTokenForm):
    if request.method.lower() == 'get':
        if 'oauth_token' not in request.GET:
            return HttpResponseBadRequest('No request token specified.')
        incoming_token = request.GET['oauth_token']
    elif request.method.lower() == 'post':
        if 'oauth_token' not in request.POST:
            return HttpResponseBadRequest('No request token specified.')
        incoming_token = request.POST['oauth_token']

    oauth_request = get_oauth_request(request)

    try:
        request_token = store.get_request_token(
            request, oauth_request, incoming_token)
    except InvalidTokenError:
        return HttpResponse('Invalid request token: %s' % incoming_token, status=401)

    consumer = store.get_consumer_for_request_token(
        request, oauth_request, request_token)

    # LRS CHANGE - MAKE SURE LOGGED IN USER OWNS THIS CONSUMER
    if request.user != consumer.user:
        return HttpResponseForbidden('Invalid user for this client.')

    if request.method == 'POST':
        form = form_class(request.POST)
        if request.session.get('oauth', '') == request_token.key and form.is_valid():
            request.session['oauth'] = ''
            if form.cleaned_data['authorize_access']:
                request_token = store.authorize_request_token(
                    request, oauth_request, request_token)
                args = {'oauth_token': request_token.key}
            else:
                args = {'error': _('Access not granted by user.')}
            if request_token.callback is not None and request_token.callback != OUT_OF_BAND:
                callback_url = request_token.get_callback_url(args)
                if UNSAFE_REDIRECTS:
                    response = UnsafeRedirect(callback_url)
                else:
                    response = HttpResponseRedirect(callback_url)
            else:
                # try to get custom callback view
                callback_view_str = getattr(settings, OAUTH_CALLBACK_VIEW,
                                            'oauth_provider.views.fake_callback_view')
                try:
                    view_callable = get_callable(callback_view_str)
                except AttributeError:
                    raise Exception("%s view doesn't exist." % callback_view_str)

                # try to treat it as Class Based View (CBV)
                try:
                    callback_view = view_callable.as_view()
                except AttributeError:
                    # if it appears not to be CBV treat it like FBV
                    callback_view = view_callable

                response = callback_view(request, **args)
        else:
            response = send_oauth_error('https' if request.is_secure() else 'http',
                get_current_site(request).domain,
                oauth.Error(_('Action not allowed.')))
    else:
        # try to get custom authorize view
        authorize_view_str = getattr(settings, OAUTH_AUTHORIZE_VIEW,
                                     'oauth_provider.views.fake_authorize_view')
        try:
            view_callable = get_callable(authorize_view_str)
        except AttributeError:
            raise Exception("%s view doesn't exist." % authorize_view_str)

        # try to treat it as Class Based View (CBV)
        try:
            authorize_view = view_callable.as_view()
        except AttributeError:
            # if it appears not to be CBV treat it like FBV
            authorize_view = view_callable

        params = oauth_request.get_normalized_parameters()
        # set the oauth flag
        request.session['oauth'] = request_token.key
        response = authorize_view(
            request, request_token, request_token.get_callback_url(), params)

    return response

Example 62

Project: ADL_LRS
Source File: views.py
View license
@csrf_exempt
def access_token(request):
    oauth_request = get_oauth_request(request)
    if oauth_request is None:
        return HttpResponseBadRequest('Invalid request parameters.')

    # Consumer
    try:
        consumer = store.get_consumer(
            request, oauth_request, oauth_request['oauth_consumer_key'])
    except InvalidConsumerError:
        return HttpResponseBadRequest('Invalid consumer.')

    is_xauth = is_xauth_request(oauth_request)

    if not is_xauth:

        # Check Parameters
        missing_params = require_params(
            oauth_request, ('oauth_token', 'oauth_verifier'))
        if missing_params is not None:
            return missing_params

        # Check Request Token
        try:
            request_token = store.get_request_token(
                request, oauth_request, oauth_request['oauth_token'])
        except InvalidTokenError:
            return HttpResponse('Invalid request token: %s' % oauth_request['oauth_token'], status=401)
        if not request_token.is_approved:
            return HttpResponse('Request Token not approved by the user.', status=401)

        # Verify Signature
        if not verify_oauth_request(request, oauth_request, consumer, request_token):
            return HttpResponseBadRequest('Could not verify OAuth request.')

        # Check Verifier
        if oauth_request.get('oauth_verifier', None) != request_token.verifier:
            return HttpResponseBadRequest('Invalid OAuth verifier.')

    else:  # xAuth

        # Check Parameters
        missing_params = require_params(
            oauth_request, ('x_auth_username', 'x_auth_password', 'x_auth_mode'))
        if missing_params is not None:
            return missing_params

        # Check if Consumer allows xAuth
        if not consumer.xauth_allowed:
            return HttpResponseBadRequest('xAuth not allowed for this method')

        # Check Signature
        if not verify_oauth_request(request, oauth_request, consumer):
            return HttpResponseBadRequest('Could not verify xAuth request.')

        user = authenticate(
            x_auth_username=oauth_request.get_parameter('x_auth_username'),
            x_auth_password=oauth_request.get_parameter('x_auth_password'),
            x_auth_mode=oauth_request.get_parameter('x_auth_mode')
        )

        if not user:
            return HttpResponseBadRequest('xAuth username or password is not valid')
        else:
            request.user = user

        # Handle Request Token
        try:
            # request_token = store.create_request_token(request, oauth_request, consumer, oauth_request.get('oauth_callback'))
            request_token = store.create_request_token(
                request, oauth_request, consumer, OUT_OF_BAND)
            request_token = store.authorize_request_token(
                request, oauth_request, request_token)
        except oauth.Error as err:
            return send_oauth_error('https' if request.is_secure() else 'http',
                get_current_site(request).domain, err)

    access_token = store.create_access_token(
        request, oauth_request, consumer, request_token)

    ret = urlencode({
        'oauth_token': access_token.key,
        'oauth_token_secret': access_token.secret
    })
    return HttpResponse(ret, content_type='application/x-www-form-urlencoded')

Example 63

Project: hue
Source File: wsgi.py
View license
    def __call__(self, environ, start_response):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            with self.initLock:
                try:
                    # Check that middleware is still uninitialised.
                    if self._request_middleware is None:
                        self.load_middleware()
                except:
                    # Unload whatever middleware we got
                    self._request_middleware = None
                    raise

        set_script_prefix(base.get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            request = self.request_class(environ)
        except UnicodeDecodeError:
            logger.warning('Bad Request (UnicodeDecodeError)',
                exc_info=sys.exc_info(),
                extra={
                    'status_code': 400,
                }
            )
            response = http.HttpResponseBadRequest()
        else:
            response = self.get_response(request)

        response._handler_class = self.__class__

        status = '%s %s' % (response.status_code, response.reason_phrase)
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        for c in response.cookies.values():
            response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
        start_response(force_str(status), response_headers)
        return response

Example 64

Project: 1flow
Source File: share.py
View license
def share_one(request, item_id):
    """ Base view for sharing an article / read. """

    user = request.user

    def format_recipients(recipients):

        def pretty_name(recipient):
            return recipient.username \
                if recipient.is_active else recipient.email

        first = recipients.pop(0)

        recipients_len = len(recipients)

        if recipients_len == 0:
            return pretty_name(first)

        if recipients_len > 1:
            return _(u'{0} and {1} other persons').format(
                pretty_name(first), recipients_len)

        return _(u'{0} and another person').format(
            pretty_name(first))

    if not request.is_ajax():
        return HttpResponseBadRequest(u'Ajax is needed for this…')

    try:
        item = get_object_or_404(BaseItem, id=int(item_id))
        read = request.user.reads.get(item=item)

    except:
        LOGGER.exception(u'Could not load things to share item #%s',
                         item_id)
        return HttpResponseTemporaryServerError('BOOM')

    user_share_lock = user.share_lock
    user_share_lock.acquire()

    if request.POST:
        form = ReadShareForm(request.POST, user=request.user)

        if form.is_valid():
            message, recipients = form.save()

            if recipients:
                # Creating new friends on the fly will make
                # new accounts active by default. New friends
                # will be able to login straight ahead.
                recipients = User.get_from_emails(recipients,
                                                  create_active=True)

                try:
                    # HEADS UP: we NEED to create a new poke if the message
                    # changed. This gracefully handles the case where user A
                    # shares item I with user B with a personnal/confidential
                    # message, then shares it again with user C with a more
                    # standard message.
                    #
                    # Without the `message` field, user C will get the private
                    # message redacted for user B, which absolutely not what we
                    # want.
                    #
                    # But, if user A doesn't change the message between pokes,
                    # we can pack the recipients on the same poke in database,
                    # which seems always a good thing to save some space and
                    # avoid DB scans.

                    poke = Poke.objects.get(user=request.user,
                                            attachments=item,
                                            # `message` is *very* important,
                                            # see comment above.
                                            message=message)
                    created = False

                except Poke.DoesNotExist:
                    poke = Poke.create_poke(
                        sender=request.user,
                        message=message,
                        recipients=recipients,
                        attachments=[item],
                    )
                    created = True

                except Exception, e:
                    LOGGER.exception('sharing article via poke failed')
                    messages.warning(
                        request, _(u'Sharing article failed: {0}').format(e),
                        extra_tags='sticky safe')
                    poke = None

                if poke is not None:
                    if not created:
                        new_recipients = [r for r in recipients
                                          if r not in poke.recipients.all()]

                        if new_recipients:
                            poke.resend(recipients=new_recipients)

                    messages.info(request,
                                  _(u'Successfully shared <em>{0}</em> '
                                    u'with {1}').format(
                                      read.item.name,
                                      format_recipients(list(recipients)[:])),
                                  extra_tags='safe')

                user_share_lock.release()

            else:
                messages.success(
                    request,
                    _(u'OK, I will tenderly keep <em>{0}</em> '
                      u'for yourself only.').format(read.item.name),
                    extra_tags='safe')

            return render(request, u'snippets/share/share-one-result.html')

    else:
        form = ReadShareForm(user=request.user)

    user_share_lock.release()

    return render(request, u'snippets/share/share-one.html',
                  {'read': read, 'form': form})

Example 65

Project: 1flow
Source File: __init__.py
View license
@token_protected
def export_content(request, **kwargs):
    """ Export recent feeds/articles as JSON. """

    since = kwargs.get('since')
    until = kwargs.get('until', None)
    format = request.GET.get('format', 'json')
    folder_id = kwargs.get('folder_id', None)
    folder_slug = kwargs.get('folder_slug', None)

    if folder_id:
        folder = get_object_or_404(Folder, id=folder_id)

    elif folder_slug:
        folder = get_object_or_404(Folder, slug=folder_slug)

    else:
        try:
            default_user_config = Configuration.objects.get(
                name='export_feeds_default_user')

        except Configuration.DoesNotExist:
            folder = None

        else:
            folder = User.objects.get(
                username=default_user_config.value).root_folder

    if format == 'json':

        def content_generator():

            pretty_print = human_user_agent(request)
            new_lines = u'\n' if pretty_print else u''
            indentation = u'  ' if pretty_print else u''

            yield u'{{{0}{1}"data":{0}{1}{1}[{0}'.format(new_lines,
                                                         indentation)

            data_chunked = 0

            try:
                for chunk, last in lookahead(BaseFeed.export_content(
                                             since, until, folder=folder)):

                    if last:
                        format_string = u'{1}{1}{1}{2}{0}'

                    else:
                        format_string = u'{1}{1}{1}{2},{0}'

                    # With JSON util, we overcome the now-traditional
                    # "datetime is not JSON serializable" error.
                    yield format_string.format(
                        new_lines,
                        indentation,
                        json.dumps(
                            chunk,
                            default=json_util.default,
                            indent=2
                            if pretty_print else None,

                            separators=(',', ': ')
                            if pretty_print else (',', ':'),
                        )
                    )

                    data_chunked += 1

            except Exception as e:
                LOGGER.exception(u'Could not export content')

                # ID is unavailable if the exception
                # happens in the low-level WSGI.
                yield u'{1}{1}],{0}{1}{1}"sentry_id": "{2}",{0}'.format(
                    new_lines, indentation,
                    getattr(request, 'sentry', {'id': 'unavailable'})['id'])

                yield u'{1}{1}"exception": "{2}",{0}'.format(
                    new_lines, indentation, unicode(e))

                yield u'{1}{1}"result": "ERR"{0}}}'.format(
                    new_lines, indentation)

            else:
                yield u'{1}{1}],{0}{1}{1}"result": "OK"{0}}}'.format(
                    new_lines, indentation)

        response = StreamingHttpResponse(content_generator(),
                                         content_type="application/json")

        response['Content-Disposition'] = 'attachment; filename="export.json"'
        return response
    else:
        return HttpResponseBadRequest(u'Unknown format “%s”' % format)

Example 66

Project: 1flow
Source File: __init__.py
View license
def edit_field(request, klass, oid, form_class):
    """ Edit any object field, with minimal permissions checking, via Ajax.

    For permission to succeed, request.user must be staff or the owner
    of the object.

    The form class can define an optional ``redirect_url`` attribute. This
    attribute will be used after form save (when valid) to redirect the user
    instead of just displaying him/her a notification and staying on the
    current page.
    """

    if not request.is_ajax():
        return HttpResponseBadRequest('This request needs Ajax')

    try:
        obj_class = globals()[klass]

    except KeyError:
        LOGGER.exception(u'KeyError on “%s” in edit! Model not imported?',
                         klass)
        return HttpResponseTemporaryServerError()

    if 'history_id' in (x.name for x in obj_class._meta.fields):
        obj = get_object_or_404(obj_class, history_id=oid)

    else:
        obj = get_object_or_404(obj_class, id=oid)

    try:
        if obj.user != request.user \
                and not request.user.is_staff_or_superuser_and_enabled:
            return HttpResponseForbidden(u'Not owner nor superuser/staff')

    except AttributeError:
        if not request.user.is_staff_or_superuser_and_enabled:
            return HttpResponseForbidden(
                u'Not superuser/staff and no owner/creator field on instance')
    try:
        instance_name = obj.name

    except:
        instance_name = unicode(obj)

    form_klass = getattr(forms, form_class)

    if request.POST:
        form_get_args = request.GET.copy()

        if bool(form_get_args):
            form = form_klass(request.POST, instance=obj,
                              form_get_args=form_get_args)

        else:
            form = form_klass(request.POST, instance=obj)

        redirect_url = None

        if form.is_valid():
            obj = form.save(request.user)

            try:
                redirect_url = form.redirect_url

            except AttributeError:
                # The form didn't set it, this is a supported behavior.
                # Just do as usual and simply render the JS template.
                pass

        return render(request,
                      'snippets/edit_field/result.html',
                      {
                          'instance_name': instance_name,
                          'form': form,
                          'obj': obj,
                          'field_name': [f for f in form][0].name,
                          'form_class': form_class,
                          'klass': klass,
                          'redirect_url': redirect_url,
                      })

    else:
        form_get_args = request.GET.copy()

        if bool(form_get_args):
            form = form_klass(instance=obj, form_get_args=form_get_args)

        else:
            form = form_klass(instance=obj)

    return render(request,
                  'snippets/edit_field/modal.html',
                  {
                      'instance_name': instance_name,
                      'form': form,
                      'obj': obj,
                      'field_name': [f for f in form][0].name,
                      'form_class': form_class,
                      'klass': klass,
                  })

Example 67

Project: django-lazysignup
Source File: views.py
View license
@allow_lazy_user
def convert(request, form_class=None,
            redirect_field_name='redirect_to',
            anonymous_redirect=settings.LOGIN_URL,
            template_name='lazysignup/convert.html',
            ajax_template_name='lazysignup/convert_ajax.html'):
    """ Convert a temporary user to a real one. Reject users who don't
    appear to be temporary users (ie. they have a usable password)
    """
    redirect_to = 'lazysignup_convert_done'

    if form_class is None:
        if constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM is not None:
            form_class = import_string(constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM)
        else:
            form_class = UserCreationForm

    # If we've got an anonymous user, redirect to login
    if request.user.is_anonymous():
        return HttpResponseRedirect(anonymous_redirect)

    if request.method == 'POST':
        redirect_to = request.POST.get(redirect_field_name) or redirect_to
        form = form_class(request.POST, instance=request.user)
        if form.is_valid():
            try:
                LazyUser.objects.convert(form)
            except NotLazyError:
                # If the user already has a usable password, return a Bad
                # Request to an Ajax client, or just redirect back for a
                # regular client.
                if request.is_ajax():
                    return HttpResponseBadRequest(
                        content=_(u"Already converted."))
                else:
                    return redirect(redirect_to)

            # Re-log the user in, as they'll now not be authenticatable with
            # the Lazy backend
            login(request, authenticate(**form.get_credentials()))

            # If we're being called via AJAX, then we just return a 200
            # directly to the client. If not, then we redirect to a
            # confirmation page or to redirect_to, if it's set.
            if request.is_ajax():
                return HttpResponse()
            else:
                return redirect(redirect_to)

        # Invalid form, now check to see if is an ajax call
        if request.is_ajax():
            return HttpResponseBadRequest(content=str(form.errors))
    else:
        form = form_class()

    # If this is an ajax request, prepend the ajax template to the list of
    # templates to be searched.
    if request.is_ajax():
        template_name = [ajax_template_name, template_name]
    return render(
        request,
        template_name,
        {
            'form': form,
            'redirect_to': redirect_to
        },
    )

Example 68

Project: django-riv
Source File: resources.py
View license
    @csrf_exempt
    def handle_request(self, request, *args, **kwargs):
        rest_info = RestInformation(self._meta)

        req_meth = request.method.upper()
        req_type = self._get_request_type(req_meth, kwargs)

        rest_info.request_method  = req_meth
        rest_info.request_type    = req_type
        rest_info.allowed_methods = self._http_allowed_methods(req_type)
        rest_info.format          = get_available_format(request)

        if not rest_info.format:
            if self._meta.fallback_on_unsupported_format:
                # TODO global constant
                rest_info.format = 'json'
            else:
                return HttpResponseNotAcceptable()

        if not self._check_method(req_meth, req_type):
            return HttpResponseNotAllowed(allow_headers=rest_info.allowed_methods)

        # Add an is_rest() method to the request (returning True)
        request.is_rest = lambda: True

        # Make the RestInformation object available in the views.
        request.rest_info = rest_info

        # An exception signals malformed input data resulting
        # in a 400 Bad Request response.
        try:
            self.read_raw_data(request)
        except Exception, e:
            if settings.DEBUG and self.display_errors:
                raise
            else:
                return HttpResponseBadRequest()

        try:
            handling_method = self._wrapper.get_handler_for('%s_%s' % (req_meth, req_type))
        except AttributeError:
            if settings.DEBUG and self.display_errors:
                raise
            else:
                raise Http404()

        self.pre_view(request)

        handling_exception = None
        response = None
        try:
            response = handling_method(request, *args, **kwargs)
        except AttributeError, e:
            # Most probably this signals a malformed chain of commands.
            if settings.DEBUG and self.display_errors:
                raise
            else:
                return HttpResponseNotImplemented()
        except Exception, e:
            handling_exception = e

        self.post_view(
            request=request, 
            response=response, 
            exception=handling_exception
        )

        return self._response_postprocessing(
            request=request, 
            response=response, 
            exception=handling_exception
        )

Example 69

Project: decode-Django
Source File: wsgi.py
View license
    def __call__(self, environ, start_response):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.

        # 这里的检测: 因为 self._request_middleware 是最后才设定的, 所以如果为空,
        # 很可能是因为 self.load_middleware() 没有调用成功.
        if self._request_middleware is None:
            with self.initLock:
                try:
                    # Check that middleware is still uninitialised.
                    if self._request_middleware is None:
                        因为 load_middleware() 可能没有调用, 调用一次.
                        self.load_middleware()
                except:
                    # Unload whatever middleware we got
                    self._request_middleware = None
                    raise

        set_script_prefix(base.get_script_name(environ))
        signls.request_started.send(sender=self.__class__) # __class__ 代表自己的类

        try:
            # 实例化 request_class = WSGIRequest, 将在日后文章中展开, 可以将其视为一个代表 http 请求的类
            request = self.request_class(environ)

        except UnicodeDecodeError:
            logger.warning('Bad Request (UnicodeDecodeError)',
                exc_info=sys.exc_info(),
                extra={
                    'status_code': 400,
                }
            )
            response = http.HttpResponseBadRequest()
        else:
            # 调用 self.get_response(), 将会返回一个相应对象 response
            response = self.get_response(request)

        # 将 self 挂钩到 response 对象
        response._handler_class = self.__class__

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'

         # 状态码
        status = '%s %s' % (response.status_code, status_text)

        response_headers = [(str(k), str(v)) for k, v in response.items()]

        # 对于每个一个 cookie, 都在 header 中设置: Set-cookie xxx=yyy
        for c in response.cookies.values():
            response_headers.append((str('Set-Cookie'), str(c.output(header=''))))

        # start_response() 操作已经在上节中介绍了
        start_response(force_str(status), response_headers)

        # 成功返回相应对象
        return response

Example 70

Project: django-compositepks
Source File: modpython.py
View license
    def __call__(self, req):
        # mod_python fakes the environ, and thus doesn't process SetEnv.  This fixes that
        os.environ.update(req.subprocess_env)

        # now that the environ works we can see the correct settings, so imports
        # that use settings now can work
        from django.conf import settings

        # if we need to set up middleware, now that settings works we can do it now.
        if self._request_middleware is None:
            self.load_middleware()

        set_script_prefix(req.get_options().get('django.root', ''))
        signals.request_started.send(sender=self.__class__)
        try:
            try:
                request = self.request_class(req)
            except UnicodeDecodeError:
                response = http.HttpResponseBadRequest()
            else:
                response = self.get_response(request)

                # Apply response middleware
                for middleware_method in self._response_middleware:
                    response = middleware_method(request, response)
                response = self.apply_response_fixes(request, response)
        finally:
            signals.request_finished.send(sender=self.__class__)

        # Convert our custom HttpResponse object back into the mod_python req.
        req.content_type = response['Content-Type']
        for key, value in response.items():
            if key != 'content-type':
                req.headers_out[str(key)] = str(value)
        for c in response.cookies.values():
            req.headers_out.add('Set-Cookie', c.output(header=''))
        req.status = response.status_code
        try:
            for chunk in response:
                req.write(chunk)
        finally:
            response.close()

        return 0 # mod_python.apache.OK

Example 71

Project: noteshrinker-django
Source File: views.py
View license
@require_POST
def shrink(request):
    files = request.POST.getlist('files[]')
    existing_files = []
    for i in files:
        path = os.path.join(settings.MEDIA_ROOT, 'pictures', i)
        if os.path.exists(path):
            existing_files.append(path)
    if len(existing_files) == 0:
        return Http404
    on_off = lambda x: True if x == 'on' else False
    try:
        num_colors = int(request.POST['num_colors'])
        sample_fraction = float(request.POST['sample_fraction']) * 0.01
        sat_threshold = float(request.POST['sat_threshold'])
        value_threshold = float(request.POST['value_threshold'])
    except ValueError as e:
        return HttpResponseBadRequest(str(e))
    if request.POST['pdfname'].find('.pdf') == -1:

        pdfname = random_string(settings.RANDOM_STRING_LEN) + "_" + request.POST['pdfname'] + '.pdf'
    else:
        pdfname = random_string(settings.RANDOM_STRING_LEN) + "_" + request.POST['pdfname']

    basename = random_string(settings.RANDOM_STRING_LEN) + "_" + request.POST['basename']
    options = {
        "basename": basename,  # базовое название для картинки
        "filenames": existing_files,  # массив путей к файлам
        "global_palette": on_off(request.POST['global_palette']),  # одна палитра для всех картинок
        "num_colors": num_colors,  # цветов на выходе
        "pdf_cmd": 'convert %i %o',  # команда для пдф
        "pdfname": os.path.join(settings.PDF_ROOT, pdfname),  # название выходного пдф файла
        "postprocess_cmd": None,
        "postprocess_ext": '_post.png',  # название после процессинга (?)
        "quiet": False,  # сократить выдачу
        "sample_fraction": sample_fraction,  # пикселей брать за образец в %
        "sat_threshold": sat_threshold,  # насыщенность фона
        "saturate": True,  # насыщать
        "sort_numerically": on_off(request.POST['sort_numerically']),  # оставить порядок следования
        "value_threshold": value_threshold,  # пороговое значение фона
        "white_bg": on_off(request.POST['white_bg']),  # белый фон
        "picture_folder": settings.PNG_ROOT  # куда сохранять картинки
    }
    pngs, pdf = notescan_main(AttrDict(options))

    return JsonResponse({"pngs": pngs, "pdf": pdfname})

Example 72

Project: django-cms
Source File: placeholderadmin.py
View license
    @xframe_options_sameorigin
    def add_plugin(self, request):
        """
        Shows the add plugin form and saves it on POST.

        Requires the following GET parameters:
            - placeholder_id
            - plugin_type
            - plugin_language
            - plugin_parent (optional)
            - plugin_position (optional)
        """
        form = PluginAddValidationForm(request.GET)

        if not form.is_valid():
            # list() is necessary for python 3 compatibility.
            # errors is s dict mapping fields to a list of errors
            # for that field.
            error = list(form.errors.values())[0][0]
            return HttpResponseBadRequest(force_text(error))

        plugin_data = form.cleaned_data
        placeholder = plugin_data['placeholder_id']
        plugin_type = plugin_data['plugin_type']

        if not self.has_add_plugin_permission(request, placeholder, plugin_type):
            message = force_text(_('You do not have permission to add a plugin'))
            return HttpResponseForbidden(message)

        parent = plugin_data.get('plugin_parent')

        if parent:
            position = parent.cmsplugin_set.count()
        else:
            position = CMSPlugin.objects.filter(
                parent__isnull=True,
                language=plugin_data['plugin_language'],
                placeholder=placeholder,
            ).count()

        plugin_data['position'] = position

        plugin_class = plugin_pool.get_plugin(plugin_type)
        plugin_instance = plugin_class(plugin_class.model, self.admin_site)

        # Setting attributes on the form class is perfectly fine.
        # The form class is created by modelform factory every time
        # this get_form() method is called.
        plugin_instance._cms_initial_attributes = {
            'language': plugin_data['plugin_language'],
            'placeholder': plugin_data['placeholder_id'],
            'parent': plugin_data.get('plugin_parent', None),
            'plugin_type': plugin_data['plugin_type'],
            'position': plugin_data['position'],
        }

        response = plugin_instance.add_view(request)

        if request.method == "POST" and plugin_instance.object_successfully_changed:
            self.post_add_plugin(request, plugin_instance.saved_object)
        return response

Example 73

Project: django-cms
Source File: placeholderadmin.py
View license
    @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')

Example 74

Project: django-cms
Source File: placeholderadmin.py
View license
    @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')

Example 75

Project: django-fluent-comments
Source File: views.py
View license
@csrf_protect
@require_POST
def post_comment_ajax(request, using=None):
    """
    Post a comment, via an Ajax call.
    """
    if not request.is_ajax():
        return HttpResponseBadRequest("Expecting Ajax call")

    # This is copied from django_comments.
    # Basically that view does too much, and doesn't offer a hook to change the rendering.
    # The request object is not passed to next_redirect for example.
    #
    # This is a separate view to integrate both features. Previously this used django-ajaxcomments
    # which is unfortunately not thread-safe (it it changes the comment view per request).

    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest("Missing content_type or object_pk field.")
    try:
        model = get_django_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
    except ValueError:
        return CommentPostBadRequest("Invalid object_pk value: {0}".format(escape(object_pk)))
    except TypeError:
        return CommentPostBadRequest("Invalid content_type value: {0}".format(escape(ctype)))
    except AttributeError:
        return CommentPostBadRequest("The given content-type {0} does not resolve to a valid model.".format(escape(ctype)))
    except ObjectDoesNotExist:
        return CommentPostBadRequest("No object matching content-type {0} and object PK {1} exists.".format(escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest("Attempting go get content-type {0!r} and object PK {1!r} exists raised {2}".format(escape(ctype), escape(object_pk), e.__class__.__name__))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = get_comments_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest("The comment form failed security verification: {0}".format(form.security_errors()))

    # If there are errors or if we requested a preview show the comment
    if preview:
        comment = form.get_comment_object() if not form.errors else None
        return _ajax_result(request, form, "preview", comment, object_id=object_pk)
    if form.errors:
        return _ajax_result(request, form, "post", object_id=object_pk)

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )

    for (receiver, response) in responses:
        if response is False:
            return CommentPostBadRequest("comment_will_be_posted receiver {0} killed the comment".format(receiver.__name__))

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )

    return _ajax_result(request, form, "post", comment, object_id=object_pk)

Example 76

Project: django-ses
Source File: views.py
View license
@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()

Example 77

Project: satchmo
Source File: views.py
View license
def notify_callback(request):
    payment_module = config_get_group('PAYMENT_SERMEPA')
    if payment_module.LIVE.value:
        log.debug("Live IPN on %s", payment_module.KEY.value)
        signature_code = payment_module.MERCHANT_SIGNATURE_CODE.value
        terminal = payment_module.MERCHANT_TERMINAL.value
    else:
        log.debug("Test IPN on %s", payment_module.KEY.value)
        signature_code = payment_module.MERCHANT_TEST_SIGNATURE_CODE.value
        terminal = payment_module.MERCHANT_TEST_TERMINAL.value
    data = request.POST
    log.debug("Transaction data: " + repr(data))
    try:
        sig_data = "%s%s%s%s%s%s" % (
                data['Ds_Amount'],
                data['Ds_Order'],
                data['Ds_MerchantCode'],
                data['Ds_Currency'],
                data['Ds_Response'],
                signature_code
                )
        sig_calc = sha1(sig_data).hexdigest()
        if sig_calc != data['Ds_Signature'].lower():
            log.error("Invalid signature. Received '%s', calculated '%s'." % (data['Ds_Signature'], sig_calc))
            return HttpResponseBadRequest("Checksum error")
        if data['Ds_MerchantCode'] != payment_module.MERCHANT_FUC.value:
            log.error("Invalid FUC code: %s" % data['Ds_MerchantCode'])
            return HttpResponseNotFound("Unknown FUC code")
        if int(data['Ds_Terminal']) != int(terminal):
            log.error("Invalid terminal number: %s" % data['Ds_Terminal'])
            return HttpResponseNotFound("Unknown terminal number")
        # TODO: fields Ds_Currency, Ds_SecurePayment may be worth checking

        xchg_order_id = data['Ds_Order']
        try:
            order_id = xchg_order_id[:xchg_order_id.index('T')]
        except ValueError:
            log.error("Incompatible order ID: '%s'" % xchg_order_id)
            return HttpResponseNotFound("Order not found")
        try:
            order = Order.objects.get(id=order_id)
        except Order.DoesNotExist:
            log.error("Received data for nonexistent Order #%s" % order_id)
            return HttpResponseNotFound("Order not found")
        amount = Decimal(data['Ds_Amount']) / Decimal('100')    # is in cents, divide it
        if int(data['Ds_Response']) > 100:
            log.info("Response code is %s. Payment not accepted." % data['Ds_Response'])
            return HttpResponse()
    except KeyError:
        log.error("Received incomplete SERMEPA transaction data")
        return HttpResponseBadRequest("Incomplete data")
    # success
    order.add_status(status='New', notes=u"Paid through SERMEPA.")
    processor = get_processor_by_key('PAYMENT_SERMEPA')
    payment = processor.record_payment(
        order=order,
        amount=amount,
        transaction_id=data['Ds_AuthorisationCode'])
    # empty customer's carts
    for cart in Cart.objects.filter(customer=order.contact):
        cart.empty()
    return HttpResponse()

Example 78

Project: drawquest-web
Source File: views.py
View license
def sql_profile(request):
    """
    Returns the output of running the SQL and getting the profiling statistics.

    Expected GET variables:
        sql: urlencoded sql with positional arguments
        params: JSON encoded parameter values
        duration: time for SQL to execute passed in from toolbar just for redisplay
        hash: the hash of (secret + sql + params) for tamper checking
    """
    from debug_toolbar.panels.sql import reformat_sql
    sql = request.GET.get('sql', '')
    params = request.GET.get('params', '')
    hash = sha1(settings.SECRET_KEY + sql + params).hexdigest()
    if hash != request.GET.get('hash', ''):
        return HttpResponseBadRequest('Tamper alert') # SQL Tampering alert
    if sql.lower().strip().startswith('select'):
        params = simplejson.loads(params)
        cursor = connection.cursor()
        result = None
        headers = None
        result_error = None
        try:
            cursor.execute("SET PROFILING=1") # Enable profiling
            cursor.execute(sql, params) # Execute SELECT
            cursor.execute("SET PROFILING=0") # Disable profiling
            # The Query ID should always be 1 here but I'll subselect to get the last one just in case...
            cursor.execute("SELECT * FROM information_schema.profiling WHERE query_id=(SELECT query_id FROM information_schema.profiling ORDER BY query_id DESC LIMIT 1)")
            headers = [d[0] for d in cursor.description]
            result = cursor.fetchall()
        except:
            result_error = "Profiling is either not available or not supported by your database."
        cursor.close()
        context = {
            'result': result,
            'result_error': result_error,
            'sql': reformat_sql(cursor.db.ops.last_executed_query(cursor, sql, params)),
            'duration': request.GET.get('duration', 0.0),
            'headers': headers,
        }
        return render_to_response('debug_toolbar/panels/sql_profile.html', context)
    raise InvalidSQLError("Only 'select' queries are allowed.")

Example 79

Project: editorsnotes-server
Source File: projects.py
View license
@login_required
@reversion.create_revision()
def project_roster(request, project_slug):
    o = {}
    user = request.user


    project_qs = Project.objects\
            .prefetch_related('roles__group__permissions')\
            .select_related('roles__group__permissions',
                            'roles__group__users')
    project = get_object_or_404(project_qs, slug=project_slug)

    o['breadcrumb'] = (
        (project.name, project.get_absolute_url()),
        ('Roster', None)
    )

    can_view = user.has_project_perm(project, 'main.view_project_roster')
    if not can_view:
        return HttpResponseForbidden(VIEW_ERROR_MSG.format(project))
    can_change = user.has_project_perm(project, 'main.change_project_roster')

    ProjectRosterFormSet = forms.make_project_roster_formset(project)
    ProjectInvitationFormSet = forms.make_project_invitation_formset(project)

    if request.method == 'POST':

        if not can_change:
            return HttpResponseForbidden(CHANGE_ERROR_MSG.format(project))

        if request.POST.get('roster-TOTAL_FORMS'):
            o['roster_formset'] = ProjectRosterFormSet(request.POST, prefix='roster')
            if o['roster_formset'].is_valid():
                o['roster_formset'].save()
                messages.add_message(request, messages.SUCCESS,
                                     'Roster for {} saved.'.format(project.name))
                return HttpResponseRedirect(request.path)
            else:
                o['invitation_formset'] = ProjectInvitationFormSet(prefix='invitation')

        elif request.POST.get('invitation-TOTAL_FORMS'):
            o['invitation_formset'] = ProjectInvitationFormSet(request.POST,
                                                               prefix='invitation')
            if o['invitation_formset'].is_valid():
                for form in o['invitation_formset']:
                    if form.cleaned_data.get('DELETE', False):
                        if form.instance:
                            form.instance.delete()
                        continue
                    obj = form.save(commit=False)
                    if not obj.id:
                        if 'email' not in form.cleaned_data:
                            continue
                        obj.creator = request.user
                        obj.project = project
                    obj.save()
                messages.add_message(request, messages.SUCCESS,
                                     'Roster for {} saved.'.format(project.name))
                return HttpResponseRedirect(request.path)
            else:
                o['roster_formset'] = ProjectRosterFormSet(prefix='roster')
        else:
            return HttpResponseBadRequest()


    elif can_change:
        o['roster_formset'] = ProjectRosterFormSet(prefix='roster')
        o['invitation_formset'] = ProjectInvitationFormSet(prefix='invitation')

    o['project'] = project
    o['roster'] = [(u, project.get_role_for(u))
                   for u in project.members.order_by('-last_login')]

    return render_to_response(
        'project_roster.html', o, context_instance=RequestContext(request))

Example 80

Project: ecommerce
Source File: views.py
View license
    def get(self, request):
        partner = get_partner_for_site(request)

        sku = request.GET.get('sku', None)
        code = request.GET.get('code', None)

        if not sku:
            return HttpResponseBadRequest(_('No SKU provided.'))

        voucher = Voucher.objects.get(code=code) if code else None

        try:
            product = StockRecord.objects.get(partner=partner, partner_sku=sku).product
        except StockRecord.DoesNotExist:
            return HttpResponseBadRequest(_('SKU [{sku}] does not exist.').format(sku=sku))

        # If the product isn't available then there's no reason to continue with the basket addition
        purchase_info = request.strategy.fetch_for_product(product)
        if not purchase_info.availability.is_available_to_buy:
            msg = _('Product [{product}] not available to buy.').format(product=product.title)
            return HttpResponseBadRequest(msg)

        # If the product is not an Enrollment Code and this is a Coupon Redemption request,
        # we check to see if the user is already enrolled
        # to prevent double-enrollment and/or accidental coupon usage.
        if product.get_product_class().name != ENROLLMENT_CODE_PRODUCT_CLASS_NAME and code:
            try:
                if request.user.is_user_already_enrolled(request, product):
                    logger.warning(
                        'User [%s] attempted to repurchase the [%s] seat of course [%s]',
                        request.user.username,
                        mode_for_seat(product),
                        product.attr.course_key
                    )
                    msg = _('You are already enrolled in {course}.').format(course=product.course.name)
                    return HttpResponseBadRequest(msg)
            except (ConnectionError, SlumberBaseException, Timeout):
                msg = _('An error occurred while retrieving enrollment details. Please try again.')
                return HttpResponseBadRequest(msg)

        # At this point we're either adding an Enrollment Code product to the basket,
        # or the user is adding a Seat product for which they are not already enrolled
        prepare_basket(request, product, voucher)
        return HttpResponseRedirect(reverse('basket:summary'), status=303)

Example 81

Project: edx-platform
Source File: assets.py
View license
@require_POST
@ensure_csrf_cookie
@login_required
def _upload_asset(request, course_key):
    '''
    This method allows for POST uploading of files into the course asset
    library, which will be supported by GridFS in MongoDB.
    '''
    # Does the course actually exist?!? Get anything from it to prove its
    # existence
    try:
        modulestore().get_course(course_key)
    except ItemNotFoundError:
        # no return it as a Bad Request response
        logging.error("Could not find course: %s", course_key)
        return HttpResponseBadRequest()

    # compute a 'filename' which is similar to the location formatting, we're
    # using the 'filename' nomenclature since we're using a FileSystem paradigm
    # here. We're just imposing the Location string formatting expectations to
    # keep things a bit more consistent
    upload_file = request.FILES['file']
    filename = upload_file.name
    mime_type = upload_file.content_type
    size = get_file_size(upload_file)

    # If file is greater than a specified size, reject the upload
    # request and send a message to the user. Note that since
    # the front-end may batch large file uploads in smaller chunks,
    # we validate the file-size on the front-end in addition to
    # validating on the backend. (see cms/static/js/views/assets.js)
    max_file_size_in_bytes = settings.MAX_ASSET_UPLOAD_FILE_SIZE_IN_MB * 1000 ** 2
    if size > max_file_size_in_bytes:
        return JsonResponse({
            'error': _(
                'File {filename} exceeds maximum size of '
                '{size_mb} MB. Please follow the instructions here '
                'to upload a file elsewhere and link to it instead: '
                '{faq_url}'
            ).format(
                filename=filename,
                size_mb=settings.MAX_ASSET_UPLOAD_FILE_SIZE_IN_MB,
                faq_url=settings.MAX_ASSET_UPLOAD_FILE_SIZE_URL,
            )
        }, status=413)

    content_loc = StaticContent.compute_location(course_key, filename)

    chunked = upload_file.multiple_chunks()
    sc_partial = partial(StaticContent, content_loc, filename, mime_type)
    if chunked:
        content = sc_partial(upload_file.chunks())
        tempfile_path = upload_file.temporary_file_path()
    else:
        content = sc_partial(upload_file.read())
        tempfile_path = None

    # first let's see if a thumbnail can be created
    (thumbnail_content, thumbnail_location) = contentstore().generate_thumbnail(
        content,
        tempfile_path=tempfile_path,
    )

    # delete cached thumbnail even if one couldn't be created this time (else
    # the old thumbnail will continue to show)
    del_cached_content(thumbnail_location)
    # now store thumbnail location only if we could create it
    if thumbnail_content is not None:
        content.thumbnail_location = thumbnail_location

    # then commit the content
    contentstore().save(content)
    del_cached_content(content.location)

    # readback the saved content - we need the database timestamp
    readback = contentstore().find(content.location)
    locked = getattr(content, 'locked', False)
    response_payload = {
        'asset': _get_asset_json(
            content.name,
            content.content_type,
            readback.last_modified_at,
            content.location,
            content.thumbnail_location,
            locked
        ),
        'msg': _('Upload completed')
    }

    return JsonResponse(response_payload)

Example 82

Project: edx-platform
Source File: views.py
View license
@login_required
@use_bulk_ops
def followed_threads(request, course_key, user_id):
    """
    Ajax-only endpoint retrieving the threads followed by a specific user.
    """

    nr_transaction = newrelic.agent.current_transaction()

    course = get_course_with_access(request.user, 'load', course_key, check_if_enrolled=True)
    try:
        profiled_user = cc.User(id=user_id, course_id=course_key)

        default_query_params = {
            'page': 1,
            'per_page': THREADS_PER_PAGE,   # more than threads_per_page to show more activities
            'sort_key': 'date',
        }

        query_params = merge_dict(
            default_query_params,
            strip_none(
                extract(
                    request.GET,
                    [
                        'page',
                        'sort_key',
                        'flagged',
                        'unread',
                        'unanswered',
                    ]
                )
            )
        )

        try:
            group_id = get_group_id_for_comments_service(request, course_key)
        except ValueError:
            return HttpResponseBadRequest("Invalid group_id")
        if group_id is not None:
            query_params['group_id'] = group_id

        paginated_results = profiled_user.subscribed_threads(query_params)
        print "\n \n \n paginated results \n \n \n "
        print paginated_results
        query_params['page'] = paginated_results.page
        query_params['num_pages'] = paginated_results.num_pages
        user_info = cc.User.from_django_user(request.user).to_dict()

        with newrelic.agent.FunctionTrace(nr_transaction, "get_metadata_for_threads"):
            annotated_content_info = utils.get_metadata_for_threads(
                course_key,
                paginated_results.collection,
                request.user, user_info
            )
        if request.is_ajax():
            is_staff = has_permission(request.user, 'openclose_thread', course.id)
            return utils.JsonResponse({
                'annotated_content_info': annotated_content_info,
                'discussion_data': [
                    utils.prepare_content(thread, course_key, is_staff) for thread in paginated_results.collection
                ],
                'page': query_params['page'],
                'num_pages': query_params['num_pages'],
            })
        #TODO remove non-AJAX support, it does not appear to be used and does not appear to work.
        else:
            context = {
                'course': course,
                'user': request.user,
                'django_user': User.objects.get(id=user_id),
                'profiled_user': profiled_user.to_dict(),
                'threads': paginated_results.collection,
                'user_info': user_info,
                'annotated_content_info': annotated_content_info,
                #                'content': content,
            }

            return render_to_response('discussion/user_profile.html', context)
    except User.DoesNotExist:
        raise Http404

Example 83

Project: edx-platform
Source File: views.py
View license
@require_POST
@login_required
@permitted
def create_thread(request, course_id, commentable_id):
    """
    Given a course and commentble ID, create the thread
    """

    log.debug("Creating new thread in %r, id %r", course_id, commentable_id)
    course_key = CourseKey.from_string(course_id)
    course = get_course_with_access(request.user, 'load', course_key)
    post = request.POST
    user = request.user

    if course.allow_anonymous:
        anonymous = post.get('anonymous', 'false').lower() == 'true'
    else:
        anonymous = False

    if course.allow_anonymous_to_peers:
        anonymous_to_peers = post.get('anonymous_to_peers', 'false').lower() == 'true'
    else:
        anonymous_to_peers = False

    if 'title' not in post or not post['title'].strip():
        return JsonError(_("Title can't be empty"))
    if 'body' not in post or not post['body'].strip():
        return JsonError(_("Body can't be empty"))

    params = {
        'anonymous': anonymous,
        'anonymous_to_peers': anonymous_to_peers,
        'commentable_id': commentable_id,
        'course_id': course_key.to_deprecated_string(),
        'user_id': user.id,
        'thread_type': post["thread_type"],
        'body': post["body"],
        'title': post["title"],
    }

    # Check for whether this commentable belongs to a team, and add the right context
    if get_team(commentable_id) is not None:
        params['context'] = ThreadContext.STANDALONE
    else:
        params['context'] = ThreadContext.COURSE

    thread = cc.Thread(**params)

    # Cohort the thread if required
    try:
        group_id = get_group_id_for_comments_service(request, course_key, commentable_id)
    except ValueError:
        return HttpResponseBadRequest("Invalid cohort id")
    if group_id is not None:
        thread.group_id = group_id

    thread.save()

    thread_created.send(sender=None, user=user, post=thread)

    # patch for backward compatibility to comments service
    if 'pinned' not in thread.attributes:
        thread['pinned'] = False

    follow = post.get('auto_subscribe', 'false').lower() == 'true'

    if follow:
        cc_user = cc.User.from_django_user(user)
        cc_user.follow(thread)

    data = thread.to_dict()

    add_courseware_context([data], course, user)

    track_thread_created_event(request, course, thread, follow)

    if request.is_ajax():
        return ajax_content_response(request, course_key, data)
    else:
        return JsonResponse(prepare_content(data, course_key))

Example 84

Project: edx-platform
Source File: views.py
View license
@require_config(DonationConfiguration)
@require_POST
@login_required
def donate(request):
    """Add a single donation item to the cart and proceed to payment.

    Warning: this call will clear all the items in the user's cart
    before adding the new item!

    Arguments:
        request (Request): The Django request object.  This should contain
            a JSON-serialized dictionary with "amount" (string, required),
            and "course_id" (slash-separated course ID string, optional).

    Returns:
        HttpResponse: 200 on success with JSON-encoded dictionary that has keys
            "payment_url" (string) and "payment_params" (dictionary).  The client
            should POST the payment params to the payment URL.
        HttpResponse: 400 invalid amount or course ID.
        HttpResponse: 404 donations are disabled.
        HttpResponse: 405 invalid request method.

    Example usage:

        POST /shoppingcart/donation/
        with params {'amount': '12.34', course_id': 'edX/DemoX/Demo_Course'}
        will respond with the signed purchase params
        that the client can send to the payment processor.

    """
    amount = request.POST.get('amount')
    course_id = request.POST.get('course_id')

    # Check that required parameters are present and valid
    if amount is None:
        msg = u"Request is missing required param 'amount'"
        log.error(msg)
        return HttpResponseBadRequest(msg)
    try:
        amount = (
            decimal.Decimal(amount)
        ).quantize(
            decimal.Decimal('.01'),
            rounding=decimal.ROUND_DOWN
        )
    except decimal.InvalidOperation:
        return HttpResponseBadRequest("Could not parse 'amount' as a decimal")

    # Any amount is okay as long as it's greater than 0
    # Since we've already quantized the amount to 0.01
    # and rounded down, we can check if it's less than 0.01
    if amount < decimal.Decimal('0.01'):
        return HttpResponseBadRequest("Amount must be greater than 0")

    if course_id is not None:
        try:
            course_id = CourseLocator.from_string(course_id)
        except InvalidKeyError:
            msg = u"Request included an invalid course key: {course_key}".format(course_key=course_id)
            log.error(msg)
            return HttpResponseBadRequest(msg)

    # Add the donation to the user's cart
    cart = Order.get_cart_for_user(request.user)
    cart.clear()

    try:
        # Course ID may be None if this is a donation to the entire organization
        Donation.add_to_order(cart, amount, course_id=course_id)
    except InvalidCartItem as ex:
        log.exception(
            u"Could not create donation item for amount '%s' and course ID '%s'",
            amount,
            course_id
        )
        return HttpResponseBadRequest(unicode(ex))

    # Start the purchase.
    # This will "lock" the purchase so the user can't change
    # the amount after we send the information to the payment processor.
    # If the user tries to make another donation, it will be added
    # to a new cart.
    cart.start_purchase()

    # Construct the response params (JSON-encoded)
    callback_url = request.build_absolute_uri(
        reverse("shoppingcart.views.postpay_callback")
    )

    # Add extra to make it easier to track transactions
    extra_data = [
        unicode(course_id) if course_id else "",
        "donation_course" if course_id else "donation_general"
    ]

    response_params = json.dumps({
        # The HTTP end-point for the payment processor.
        "payment_url": get_purchase_endpoint(),

        # Parameters the client should send to the payment processor
        "payment_params": get_signed_purchase_params(
            cart,
            callback_url=callback_url,
            extra_data=extra_data
        ),
    })

    return HttpResponse(response_params, content_type="text/json")

Example 85

Project: edx-platform
Source File: middleware.py
View license
    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/', '[email protected]', 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

Example 86

Project: devmason-server
Source File: handlers.py
View license
    @allow_404
    @require_mime('json')
    @authentication_optional
    @transaction.commit_on_success
    def create(self, request, slug):
        project = get_object_or_404(Project, slug=slug)

        # Construct us the dict of "extra" info from the request
        data = request.data
        extra = request.data['client'].copy()
        for k in ('success', 'started', 'finished', 'client', 'results', 'tags'):
            extra.pop(k, None)

        # Create the Build object
        try:
            build = Build.objects.create(
                project = project,
                success = data['success'],
                started = mk_datetime(data.get('started', '')),
                finished = mk_datetime(data.get('finished', '')),
                host = data['client']['host'],
                arch = data['client']['arch'],
                user = request.user.is_authenticated() and request.user or None,

                # Because of some weirdness with the way fields are handled in
                # __init__, we have to encode extra as JSON manually here.
                # TODO: investiage why and fix JSONField
                extra_info = simplejson.dumps(extra),
            )
        except (KeyError, ValueError), ex:
            # We'll get a KeyError from request.data[k] if the given key
            # is missing and ValueError from improperly formatted dates.
            # Treat either of these as improperly formatted requests
            # and return a 400 (Bad Request)
            return HttpResponseBadRequest(str(ex))

        # Tag us a build
        if 'tags' in data:
            build.tags = ",".join(data['tags'])

        # Create each build step
        for result in request.data.get('results', []):
            # extra_info logic as above
            extra = result.copy()
            for k in ('success', 'started', 'finished', 'name', 'output', 'errout'):
                extra.pop(k, None)

            # Create the BuildStep, handling errors as above
            try:
                BuildStep.objects.create(
                    build = build,
                    success = result['success'],
                    started = mk_datetime(getattr(result, 'started', '')),
                    finished = mk_datetime(getattr(result, 'finished', '')),
                    name = result['name'],
                    output = result.get('output', ''),
                    errout = result.get('errout', ''),
                    extra_info = simplejson.dumps(extra),
                )
            except (KeyError, ValueError), ex:
                # We'll get a KeyError from request.data[k] if the given key
                # is missing and ValueError from improperly formatted dates.
                # Treat either of these as improperly formatted requests
                # and return a 400 (Bad Request)
                return HttpResponseBadRequest(str(ex))

        # It worked! Return a 201 created
        url = urlresolvers.reverse(BuildHandler.viewname, args=[project.slug, build.pk])
        return HttpResponseCreated(url)

Example 87

View license
    def get(self, request, imsi=None):
        """Handles GET requests."""
        user_profile = UserProfile.objects.get(user=request.user)
        network = user_profile.network
        try:
            subscriber = Subscriber.objects.get(imsi=imsi,
                                                network=network)
        except Subscriber.DoesNotExist:
            return HttpResponseBadRequest()

        # Queue up the recent events for the subscriber.
        events = subscriber.usageevent_set.all().order_by('-date')
        total_number_of_events = len(events)

        # Progressively filter events by start and end date, if they're
        # specified.  Cast them in the UserProfile's timezone.
        user_profile_timezone = pytz.timezone(user_profile.timezone)
        start_date = request.GET.get('start_date', None)
        if start_date:
            start_date = django_utils_timezone.make_aware(
                datetime.datetime.strptime(start_date, self.url_time_format),
                user_profile_timezone)
            now = datetime.datetime.now(pytz.UTC)
            events = events.filter(date__range=(start_date, now))
        end_date = request.GET.get('end_date', None)
        if end_date:
            end_date = django_utils_timezone.make_aware(
                datetime.datetime.strptime(end_date, self.url_time_format),
                user_profile_timezone)
            years_ago = django_utils_timezone.make_aware(
                datetime.datetime.strptime('Jan 1 2013', '%b %d %Y'),
                user_profile_timezone)
            events = events.filter(date__range=(years_ago, end_date))

        # Filter events by keyword.
        keyword = request.GET.get('keyword', '')
        if keyword:
            events = (events.filter(kind__icontains=keyword) |
                      events.filter(reason__icontains=keyword))

        # Filter the services.  If 'other' is selected, result is
        # !(any excluded options). If 'other' is not selected, result is
        # OR(selected options).
        all_services = set(['sms', 'call', 'gprs', 'transfer', 'other'])
        checked_services = request.GET.get('services', None)
        if checked_services:
            checked_services = set(checked_services.split('-'))
        else:
            # ..just assume that's a mistake and check em all.
            checked_services = all_services
        if "other" in checked_services:
            for excluded_service in all_services - checked_services:
                events = events.exclude(kind__icontains=excluded_service)
        else:
            queryset = [Q(kind__icontains=s) for s in checked_services]
            events = events.filter(reduce(operator.or_, queryset))

        # Setup the activity table with these events.
        subscriber_activity_table = django_tables.SubscriberActivityTable(
            list(events))
        tables.RequestConfig(request, paginate={'per_page': 15}).configure(
            subscriber_activity_table)

        # If start and end dates were specified, reformat them so we can inject
        # them into the datepickers.
        context_start_date, context_end_date = None, None
        if start_date:
            context_start_date = start_date.strftime(
                self.datepicker_time_format)
        if end_date:
            context_end_date = end_date.strftime(self.datepicker_time_format)

        context = {
            'networks': get_objects_for_user(request.user, 'view_network', klass=Network),
            'currency': CURRENCIES[network.subscriber_currency],
            'user_profile': user_profile,
            'subscriber': subscriber,
            'subscriber_activity_table': subscriber_activity_table,
            'total_number_of_events': total_number_of_events,
            'number_of_filtered_events': len(events),
            'keyword': keyword,
            'start_date': context_start_date,
            'end_date': context_end_date,
            'all_services': all_services,
            'checked_services': checked_services,
        }

        template = get_template('dashboard/subscriber_detail/activity.html')
        html = template.render(context, request)
        return HttpResponse(html)

Example 88

View license
    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)

Example 89

Project: feincms
Source File: tree_editor.py
View license
    def _toggle_boolean(self, request):
        """
        Handle an AJAX toggle_boolean request
        """
        try:
            item_id = int(request.POST.get('item_id', None))
            attr = str(request.POST.get('attr', None))
        except:
            return HttpResponseBadRequest("Malformed request")

        if not request.user.is_staff:
            logger.warning(
                "Denied AJAX request by non-staff \"%s\" to toggle boolean"
                " %s for object #%s", request.user, attr, item_id)
            return HttpResponseForbidden(
                _("You do not have permission to modify this object"))

        self._collect_editable_booleans()

        if attr not in self._ajax_editable_booleans:
            return HttpResponseBadRequest("not a valid attribute %s" % attr)

        try:
            obj = self.model._default_manager.get(pk=item_id)
        except self.model.DoesNotExist:
            return HttpResponseNotFound("Object does not exist")

        if not self.has_change_permission(request, obj=obj):
            logger.warning(
                "Denied AJAX request by \"%s\" to toggle boolean %s for"
                " object %s", request.user, attr, item_id)
            return HttpResponseForbidden(
                _("You do not have permission to modify this object"))

        new_state = not getattr(obj, attr)
        logger.info(
            "Toggle %s on #%d %s to %s by \"%s\"",
            attr, obj.pk, obj, "on" if new_state else "off", request.user)

        try:
            before_data = self._ajax_editable_booleans[attr](self, obj)

            setattr(obj, attr, new_state)
            obj.save()

            # Construct html snippets to send back to client for status update
            data = self._ajax_editable_booleans[attr](self, obj)

        except Exception:
            logger.exception(
                "Unhandled exception while toggling %s on %s", attr, obj)
            return HttpResponseServerError(
                "Unable to toggle %s on %s" % (attr, obj))

        # Weed out unchanged cells to keep the updates small. This assumes
        # that the order a possible get_descendents() returns does not change
        # before and after toggling this attribute. Unlikely, but still...
        return HttpResponse(
            json.dumps([b for a, b in zip(before_data, data) if a != b]),
            content_type="application/json")

Example 90

Project: lettuce
Source File: modpython.py
View license
    def __call__(self, req):
        # mod_python fakes the environ, and thus doesn't process SetEnv.  This fixes that
        os.environ.update(req.subprocess_env)

        # now that the environ works we can see the correct settings, so imports
        # that use settings now can work
        from django.conf import settings

        # if we need to set up middleware, now that settings works we can do it now.
        if self._request_middleware is None:
            self.load_middleware()

        set_script_prefix(req.get_options().get('django.root', ''))
        signals.request_started.send(sender=self.__class__)
        try:
            try:
                request = self.request_class(req)
            except UnicodeDecodeError:
                response = http.HttpResponseBadRequest()
            else:
                response = self.get_response(request)

                # Apply response middleware
                for middleware_method in self._response_middleware:
                    response = middleware_method(request, response)
                response = self.apply_response_fixes(request, response)
        finally:
            signals.request_finished.send(sender=self.__class__)

        # Convert our custom HttpResponse object back into the mod_python req.
        req.content_type = response['Content-Type']
        for key, value in response.items():
            if key != 'content-type':
                req.headers_out[str(key)] = str(value)
        for c in response.cookies.values():
            req.headers_out.add('Set-Cookie', c.output(header=''))
        req.status = response.status_code
        try:
            for chunk in response:
                req.write(chunk)
        finally:
            response.close()

        return 0 # mod_python.apache.OK

Example 91

Project: lettuce
Source File: wsgi.py
View license
    def __call__(self, environ, start_response):
        from django.conf import settings

        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            self.initLock.acquire()
            try:
                try:
                    # Check that middleware is still uninitialised.
                    if self._request_middleware is None:
                        self.load_middleware()
                except:
                    # Unload whatever middleware we got
                    self._request_middleware = None
                    raise
            finally:
                self.initLock.release()

        set_script_prefix(base.get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            try:
                request = self.request_class(environ)
            except UnicodeDecodeError:
                response = http.HttpResponseBadRequest()
            else:
                response = self.get_response(request)

                # Apply response middleware
                for middleware_method in self._response_middleware:
                    response = middleware_method(request, response)
                response = self.apply_response_fixes(request, response)
        finally:
            signals.request_finished.send(sender=self.__class__)

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'
        status = '%s %s' % (response.status_code, status_text)
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        for c in response.cookies.values():
            response_headers.append(('Set-Cookie', str(c.output(header=''))))
        start_response(status, response_headers)
        return response

Example 92

Project: Asteroid
Source File: views.py
View license
def run_web_hook(request, command, run):
    """
    The web hook lets the message queue tell us how the command got on. It 
    accepts a JSON document with the status and the output from the command.
    When we recieve it we also change the status.
    """

    # we're dealing with a post request
    if request.POST:
        try:
            # we try and get the run based on the url parameters
            existing_run = Run.objects.get(id=run, command__slug=command)

            # the web hook will only run against in progress tasks
            # so in theory should only be run once.
            if existing_run.status == "in_progress":

                # sample json input
                # json = """{
                #     "status": 0,
                #     "output": "bob2"
                # }"""
                
                # get json document from post body in request.POST
                json = request.raw_post_data

                # not try parse the JSON
                try:
                    obj = simplejson.loads(json)
                except ValueError, e:
                    # invalid input
                    return HttpResponseBadRequest()

                # get the status code and convert it to our values
                if obj['status'] == 0:
                    code = "succeeded"
                else:
                    code = "failed"

                # set the attributes on our run and save it
                existing_run.status = code # succeeded failed in_progress
                existing_run.output = obj['output']
                existing_run.save()

                # return a 200 code as everything went OK
                return HttpResponse(
                    content_type = 'application/javascript; charset=utf8'
                )

            else:
                # this run is not in progress, only the first response is recorded
                # should be client error
                return HttpResponseBadRequest()

        except Run.DoesNotExist:
            # we didn't find a run, so throw a 404
            return HttpResponseNotFound()

    else:
        # should be method not allowed as we only respond to post
        return HttpResponseNotAllowed(['POST'])

Example 93

Project: oq-engine
Source File: views.py
View license
@csrf_exempt
@cross_domain_ajax
@require_http_methods(['POST'])
def validate_nrml(request):
    """
    Leverage oq-risklib to check if a given XML text is a valid NRML

    :param request:
        a `django.http.HttpRequest` object containing the mandatory
        parameter 'xml_text': the text of the XML to be validated as NRML

    :returns: a JSON object, containing:
        * 'valid': a boolean indicating if the provided text is a valid NRML
        * 'error_msg': the error message, if any error was found
                       (None otherwise)
        * 'error_line': line of the given XML where the error was found
                        (None if no error was found or if it was not a
                        validation error)
    """
    xml_text = request.POST.get('xml_text')
    if not xml_text:
        return HttpResponseBadRequest(
            'Please provide the "xml_text" parameter')
    xml_file = writetmp(xml_text, suffix='.xml')
    try:
        nrml.parse(xml_file)
    except ExpatError as exc:
        return _make_response(error_msg=str(exc),
                              error_line=exc.lineno,
                              valid=False)
    except Exception as exc:
        # get the exception message
        exc_msg = exc.args[0]
        if isinstance(exc_msg, bytes):
            exc_msg = exc_msg.decode('utf-8')   # make it a unicode object
        elif isinstance(exc_msg, unicode):
            pass
        else:
            # if it is another kind of object, it is not obvious a priori how
            # to extract the error line from it
            return _make_response(
                error_msg=unicode(exc_msg), error_line=None, valid=False)
        # if the line is not mentioned, the whole message is taken
        error_msg = exc_msg.split(', line')[0]
        # check if the exc_msg contains a line number indication
        search_match = re.search(r'line \d+', exc_msg)
        if search_match:
            error_line = int(search_match.group(0).split()[1])
        else:
            error_line = None
        return _make_response(
            error_msg=error_msg, error_line=error_line, valid=False)
    else:
        return _make_response(error_msg=None, error_line=None, valid=True)

Example 94

Project: django-powerdns-manager
Source File: views.py
View license
@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')

Example 95

Project: golismero
Source File: wsgi.py
View license
    def __call__(self, environ, start_response):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            with self.initLock:
                try:
                    # Check that middleware is still uninitialised.
                    if self._request_middleware is None:
                        self.load_middleware()
                except:
                    # Unload whatever middleware we got
                    self._request_middleware = None
                    raise

        set_script_prefix(base.get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            request = self.request_class(environ)
        except UnicodeDecodeError:
            logger.warning('Bad Request (UnicodeDecodeError)',
                exc_info=sys.exc_info(),
                extra={
                    'status_code': 400,
                }
            )
            response = http.HttpResponseBadRequest()
        else:
            response = self.get_response(request)

        response._handler_class = self.__class__

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'
        status = '%s %s' % (response.status_code, status_text)
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        for c in response.cookies.values():
            response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
        start_response(force_str(status), response_headers)
        return response

Example 96

Project: oauth2client
Source File: views.py
View license
def oauth2_callback(request):
    """ View that handles the user's return from OAuth2 provider.

    This view verifies the CSRF state and OAuth authorization code, and on
    success stores the credentials obtained in the storage provider,
    and redirects to the return_url specified in the authorize view and
    stored in the session.

    Args:
        request: Django request.

    Returns:
         A redirect response back to the return_url.
    """
    if 'error' in request.GET:
        reason = request.GET.get(
            'error_description', request.GET.get('error', ''))
        return http.HttpResponseBadRequest(
            'Authorization failed {0}'.format(reason))

    try:
        encoded_state = request.GET['state']
        code = request.GET['code']
    except KeyError:
        return http.HttpResponseBadRequest(
            'Request missing state or authorization code')

    try:
        server_csrf = request.session[_CSRF_KEY]
    except KeyError:
        return http.HttpResponseBadRequest(
            'No existing session for this flow.')

    try:
        state = json.loads(encoded_state)
        client_csrf = state['csrf_token']
        return_url = state['return_url']
    except (ValueError, KeyError):
        return http.HttpResponseBadRequest('Invalid state parameter.')

    if client_csrf != server_csrf:
        return http.HttpResponseBadRequest('Invalid CSRF token.')

    flow = _get_flow_for_token(client_csrf, request)

    if not flow:
        return http.HttpResponseBadRequest('Missing Oauth2 flow.')

    try:
        credentials = flow.step2_exchange(code)
    except client.FlowExchangeError as exchange_error:
        return http.HttpResponseBadRequest(
            'An error has occurred: {0}'.format(exchange_error))

    get_storage(request).put(credentials)

    signals.oauth2_authorized.send(sender=signals.oauth2_authorized,
                                   request=request, credentials=credentials)

    return shortcuts.redirect(return_url)

Example 97

Project: django-secure-auth
Source File: general.py
View license
@login_decorator
def login(request, template_name='secureauth/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=BaseAuthForm,
          current_app=None, extra_context=None, redirect_to=''
          ):  # pylint: disable=R0913
    redirect_to = request.REQUEST.get(redirect_field_name, redirect_to)

    if CHECK_ATTEMPT and UserAuthAttempt.is_banned(request):
        return HttpResponseBadRequest()

    if request.method == "POST":
        form = authentication_form(
            request, data=request.POST, test_cookie_enabled=False)
        if form.is_valid():
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = settings.LOGIN_REDIRECT_URL
                if '/' not in redirect_to and '.' not in redirect_to:
                    redirect_to = reverse(settings.LOGIN_REDIRECT_URL)

            user = form.get_user()

            if UserAuthIPRange.is_blocked(request, user):
                return render(request, 'secureauth/blocked_ip.html')

            if SMS_FORCE or len(get_available_auth_methods(user)) > 1:
                data = {
                    'credentials': form.cleaned_data,
                    'user_pk': user.pk,
                    'ip': get_ip(request),
                    'redirect_to': redirect_to,
                    'extra_context': extra_context,
                }
                data = Sign().sign(data)
                return HttpResponseRedirect(
                    '%s?data=%s' % (reverse('auth_confirmation'), data))
            else:
                auth_login(request, user)

                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                if UserAuthLogging.is_enabled(request):
                    UserAuthActivity.check_location(request)
                    UserAuthActivity.log_auth(request)
                UserAuthAttempt.remove(request)
                request.session['ip'] = get_ip(request)
                return HttpResponseRedirect(redirect_to)
        elif CHECK_ATTEMPT is True:
            UserAuthAttempt.clean()
            UserAuthAttempt.store(request)
    else:
        form = authentication_form(request)

    request.session.set_test_cookie()

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(
        request, template_name, context, current_app=current_app)

Example 98

Project: django-secure-auth
Source File: general.py
View license
@login_decorator
def login_confirmation(request, template_name='secureauth/confirmation.html',
                       authentication_form=ConfirmAuthenticationForm,
                       extra_context=None, current_app=None
                       ):  # pylint: disable=R0913
    if CHECK_ATTEMPT and UserAuthAttempt.is_banned(request):
        return HttpResponseBadRequest()

    data = get_data(request)
    if extra_context is None and data.get('extra_context'):
        extra_context = data.get('extra_context')

    if hasattr(request, 'user') and request.user.is_authenticated():
        return HttpResponseRedirect(data.get('redirect_to', '/'))
    elif request.method == "POST":
        form = authentication_form(data, request.POST)
        if form.is_valid():
            user = form.get_user()

            if user and data.get('user_pk') == user.pk:
                auth_login(request, user)

                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                if UserAuthLogging.is_enabled(request):
                    UserAuthActivity.check_location(request)
                    UserAuthActivity.log_auth(
                        request, form.cleaned_data.get('auth_type'))

                UserAuthNotification.notify(request)
                UserAuthAttempt.remove(request)
                request.session['ip'] = get_ip(request)

                return HttpResponseRedirect(data.get('redirect_to'))
            else:
                return HttpResponseBadRequest()
        elif CHECK_ATTEMPT is True:
            UserAuthAttempt.clean()
            UserAuthAttempt.store(request)
    else:
        form = authentication_form(data)

    request.session.set_test_cookie()

    current_site = get_current_site(request)

    context = {
        'form': form,
        'site': current_site,
        'site_name': current_site.name,
        'data': request.GET.get('data'),
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(
        request, template_name, context, current_app=current_app)

Example 99

Project: mygpo
Source File: __init__.py
View license
@csrf_exempt
@require_valid_user
@check_username
@never_cache
@allowed_methods(['GET', 'POST'])
@cors_origin()
def episodes(request, username, version=1):

    version = int(version)
    now = datetime.utcnow()
    now_ = get_timestamp(now)
    ua_string = request.META.get('HTTP_USER_AGENT', '')

    if request.method == 'POST':
        try:
            actions = parse_request_body(request)
        except (UnicodeDecodeError, ValueError) as e:
            msg = ('Could not decode episode update POST data for ' +
                   'user %s: %s') % (username,
                   request.body.decode('ascii', errors='replace'))
            logger.warn(msg, exc_info=True)
            return HttpResponseBadRequest(msg)

        logger.info('start: user %s: %d actions from %s' % (request.user, len(actions), ua_string))

        # handle in background
        if len(actions) > dsettings.API_ACTIONS_MAX_NONBG:
            bg_handler = dsettings.API_ACTIONS_BG_HANDLER
            if bg_handler is not None:

                modname, funname = bg_handler.rsplit('.', 1)
                mod = import_module(modname)
                fun = getattr(mod, funname)

                fun(request.user, actions, now, ua_string)

                # TODO: return 202 Accepted
                return JsonResponse({'timestamp': now_, 'update_urls': []})


        try:
            update_urls = update_episodes(request.user, actions, now, ua_string)
        except ValidationError as e:
            logger.warn('Validation Error while uploading episode actions for user %s: %s', username, str(e))
            return HttpResponseBadRequest(str(e))

        except InvalidEpisodeActionAttributes as e:
            msg = 'invalid episode action attributes while uploading episode actions for user %s' % (username,)
            logger.warn(msg, exc_info=True)
            return HttpResponseBadRequest(str(e))

        logger.info('done:  user %s: %d actions from %s' % (request.user, len(actions), ua_string))
        return JsonResponse({'timestamp': now_, 'update_urls': update_urls})

    elif request.method == 'GET':
        podcast_url= request.GET.get('podcast', None)
        device_uid = request.GET.get('device', None)
        since_     = request.GET.get('since', None)
        aggregated = parse_bool(request.GET.get('aggregated', False))

        try:
            since = int(since_) if since_ else None
            if since is not None:
                since = datetime.utcfromtimestamp(since)
        except ValueError:
            return HttpResponseBadRequest('since-value is not a valid timestamp')

        if podcast_url:
            podcast = get_object_or_404(Podcast, urls__url=podcast_url)
        else:
            podcast = None

        if device_uid:

            try:
                user = request.user
                device = user.client_set.get(uid=device_uid)
            except Client.DoesNotExist as e:
                return HttpResponseNotFound(str(e))

        else:
            device = None

        changes = get_episode_changes(request.user, podcast, device, since,
                now, aggregated, version)

        return JsonResponse(changes)

Example 100

Project: mygpo
Source File: simple.py
View license
def format_podcast_list(obj_list, format, title, get_podcast=None,
        json_map=lambda x: x.url, jsonp_padding=None,
        xml_template=None, request=None, template_args={}):
    """
    Formats a list of podcasts for use in a API response

    obj_list is a list of podcasts or objects that contain podcasts
    format is one if txt, opml or json
    title is a label of the list
    if obj_list is a list of objects containing podcasts, get_podcast is the
      function used to get the podcast out of the each of these objects
    json_map is a function returning the contents of an object (from obj_list)
      that should be contained in the result (only used for format='json')
    """

    def default_get_podcast(p):
        return p

    get_podcast = get_podcast or default_get_podcast

    if format == 'txt':
        podcasts = map(get_podcast, obj_list)
        s = '\n'.join([p.url for p in podcasts] + [''])
        return HttpResponse(s, content_type='text/plain')

    elif format == 'opml':
        podcasts = map(get_podcast, obj_list)
        exporter = Exporter(title)
        opml = exporter.generate(podcasts)
        return HttpResponse(opml, content_type='text/xml')

    elif format == 'json':
        objs = list(map(json_map, obj_list))
        return JsonResponse(objs)

    elif format == 'jsonp':
        ALLOWED_FUNCNAME = string.ascii_letters + string.digits + '_'

        if not jsonp_padding:
            return HttpResponseBadRequest('For a JSONP response, specify the name of the callback function in the jsonp parameter')

        if any(x not in ALLOWED_FUNCNAME for x in jsonp_padding):
            return HttpResponseBadRequest('JSONP padding can only contain the characters %(char)s' % {'char': ALLOWED_FUNCNAME})

        objs = map(json_map, obj_list)
        return JsonResponse(objs, jsonp_padding=jsonp_padding)

    elif format == 'xml':
        if None in (xml_template, request):
            return HttpResponseBadRequest('XML is not a valid format for this request')

        podcasts = map(json_map, obj_list)
        template_args.update({'podcasts': podcasts})

        return render(request, xml_template, template_args,
                content_type='application/xml')

    else:
        return None