Python django.http 模块,HttpResponse() 实例源码

我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用django.http.HttpResponse()

项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def webfinger_view(request):
    """Generate a webfinger document."""
    q = request.GET.get("q")
    if not q:
        raise Http404()
    username = q.split("@")[0]
    if username.startswith("acct:"):
        username = username.replace("acct:", "", 1)
    user = get_object_or_404(User, username=username)
    # Create webfinger document
    webfinger = generate_legacy_webfinger(
        "diaspora",
        handle="{username}@{domain}".format(username=user.username, domain=settings.SOCIALHOME_DOMAIN),
        host=settings.SOCIALHOME_URL,
        guid=str(user.profile.guid),
        public_key=user.profile.rsa_public_key
    )
    return HttpResponse(webfinger, content_type="application/xrd+xml")
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def hcard_view(request, guid):
    """Generate a hcard document.

    For local users only.
    """
    try:
        profile = get_object_or_404(Profile, guid=guid, user__isnull=False)
    except ValueError:
        raise Http404()
    hcard = generate_hcard(
        "diaspora",
        hostname=settings.SOCIALHOME_URL,
        fullname=profile.name,
        firstname=profile.get_first_name(),
        lastname=profile.get_last_name(),
        photo300=profile.safer_image_url_large,
        photo100=profile.safer_image_url_medium,
        photo50=profile.safer_image_url_small,
        searchable="true" if profile.public else "false",
        guid=profile.guid,
        username=profile.user.username,
        public_key=profile.rsa_public_key,
    )
    return HttpResponse(hcard)
项目:django-heartbeat    作者:pbs    | 项目源码 | 文件源码
def auth(func):
    @wraps(func)
    def _decorator(request, *args, **kwargs):
        auth = get_auth()
        if auth.get('disable', False) is True:
            return func(request, *args, **kwargs)
        if 'authorized_ips' in auth:
            ip = get_client_ip(request)
            if is_authorized(ip, auth['authorized_ips']):
                return func(request, *args, **kwargs)
        prepare_credentials(auth)
        if request.META.get('HTTP_AUTHORIZATION'):
            authmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ')
            if authmeth.lower() == 'basic':
                auth = base64.b64decode(auth).decode('utf-8')
                username, password = auth.split(':')
                if (username == HEARTBEAT['auth']['username'] and
                        password == HEARTBEAT['auth']['password']):
                    return func(request, *args, **kwargs)

        response = HttpResponse(
            "Authentication failed", status=401)
        response['WWW-Authenticate'] = 'Basic realm="Welcome to 1337"'
        return response
    return _decorator
项目:WPS-4th    作者:Fastcampus-WPS    | 项目源码 | 文件源码
def index(request):
    if request.method == 'POST':
        form = SMSForm(request.POST)
        if form.is_valid():
            numbers = form.cleaned_data['recipient_numbers']
            content = form.cleaned_data['content']
            for number in numbers:
                pass
                # send_sms(number, content)
            return HttpResponse(', '.join(numbers))
    else:
        form = SMSForm(
            initial={
                'recipient_numbers': '010-2995-3874, 01029953874, 01023412, 293849323232, 02394090930',
            }
        )
    context = {
        'form': form,
    }
    return render(request, 'common/index.html', context)
项目:oscar-wagtail-demo    作者:pgovers    | 项目源码 | 文件源码
def serve(self, request):
        if "format" in request.GET:
            if request.GET['format'] == 'ical':
                # Export to ical format
                response = HttpResponse(
                    export_event(self, 'ical'),
                    content_type='text/calendar',
                )
                response['Content-Disposition'] = (
                    'attachment; filename={}.ics'.format(self.slug)
                )
                return response
            else:
                # Unrecognised format error
                message = (
                    'Could not export event\n\nUnrecognised format: {}'.format(
                        request.GET['format']
                    )
                )
                return HttpResponse(message, content_type='text/plain')
        else:
            # Display event page as usual
            return super(EventPage, self).serve(request)
项目:NearBeach    作者:robotichead    | 项目源码 | 文件源码
def serve(self, request, path):
        # the following code is largely borrowed from `django.views.static.serve`
        # and django-filetransfers: filetransfers.backends.default
        fullpath = os.path.join(settings.PRIVATE_MEDIA_ROOT, path)
        if not os.path.exists(fullpath):
            raise Http404('"{0}" does not exist'.format(fullpath))
        # Respect the If-Modified-Since header.
        statobj = os.stat(fullpath)
        content_type = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream'
        if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                                  statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
            return HttpResponseNotModified(content_type=content_type)
        response = HttpResponse(open(fullpath, 'rb').read(), content_type=content_type)
        response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
        # filename = os.path.basename(path)
        # response['Content-Disposition'] = smart_str(u'attachment; filename={0}'.format(filename))
        return response
项目:nanami    作者:theeluwin    | 项目源码 | 文件源码
def response(status, data):
    hr = HttpResponse()
    hr['Access-Control-Allow-Origin'] = '*'
    hr['Content-Type'] = 'application/json'
    hr['charset'] = 'utf-8'
    hr.status_code = status
    if type(data) == str or type(data) == unicode:
        data = {
            'message': data,
        }
    try:
        hr.write(json.dumps(data))
    except:
        try:
            hr.write(json.dumps(data, default=json_util.default))
        except:
            hr.status_code = 500
            hr.write(json.dumps({
                'error': "json serialize failed",
            }))
    return hr
项目:django_pipedrive    作者:MasAval    | 项目源码 | 文件源码
def index(request):

    enable_hstore()

    try:
        if request.method == 'POST':

            json_data = json.loads(request.body)
            meta = json_data[u'meta']

            # API v1
            if meta[u'v'] == 1:
                return handle_v1(json_data)
            else:
                raise NonImplementedVersionException()

    except IntegrityError as e:
        logging.warning(e.message)
        logging.warning("Forcing full sync from pipedrive")
        PipedriveModel.sync_from_pipedrive()

    return HttpResponse("Hello, world!")
项目:stregsystemet    作者:f-klubben    | 项目源码 | 文件源码
def find_random_image(request):
    """
    Randomly get an image and return the relative url
    """
    item = KioskItem.objects.filter(active=True).order_by('?').first()
    if item is None:
        raise Http404("No active kiosk items found")

    response_data = {
        "id": item.id,
        "url": item.image.url,
    }
    return HttpResponse(
        json.dumps(response_data),
        content_type="application/json"
    )
项目:sensu_drive    作者:ilavender    | 项目源码 | 文件源码
def resolve(request):

    mimetype = 'application/json'
    data = {}

    if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '':
        data['entity'] = request.POST['entity']        
        data['status'] = 0
        data['timestamp'] = datetime.datetime.now().timestamp()        
        data['output'] = "resolve request by %s" % (request.user.username)
        data['result'] = 'okay'

        sensu_event_resolve(data)
        Channel('background-alert').send(dict(data))


    return HttpResponse(json.dumps(data), mimetype)



#@login_required(login_url=reverse_lazy('login'))
项目:sensu_drive    作者:ilavender    | 项目源码 | 文件源码
def rmClient(request):

    mimetype = 'application/json'
    data = {}

    if request.method == 'POST' and 'client' in request.POST and request.POST['client'] != '':
        data['client'] = request.POST['client']        
        data['status'] = 0
        data['timestamp'] = datetime.datetime.now().timestamp()

        if sensu_client_delete(data):
            data['result'] = 'okay'
        else:        
            data['result'] = 'failed deleting ' + data['client']

    return HttpResponse(json.dumps(data), mimetype)


#@login_required(login_url=reverse_lazy('login'))
项目:sensu_drive    作者:ilavender    | 项目源码 | 文件源码
def twilio_say(request):

    if 'api_token' not in request.GET or request.GET['api_token'] != settings.TWILIO_CALLBACK_API_TOKEN:
        return HttpResponse('Unauthorized', status=401)

    try:
        if 'CallStatus' in request.POST:
            for k in request.POST:
                logger.debug("***twilio_say got CallStatus in request %s : %s" % (k, request.POST[k]))
    except:
        pass

    if 'msg' in request.GET and request.GET['msg'] != '':

        logger.debug("twilio_say building xml for twilio API message: [%s]" % request.GET['msg'])
        r = twiml.Response()
        r.say(request.GET['msg'], voice='alice')
        r.hangup()
        return HttpResponse(r, content_type='text/xml')

    return HttpResponse('Unauthorized', status=401)
项目:sensu_drive    作者:ilavender    | 项目源码 | 文件源码
def entity_history(request):            

    data = []
    mimetype = 'application/json'   

    if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '':

        entity = request.POST['entity']
        logger.debug("view entity_history user: %s entity: %s" % (request.user.username, entity))

        for history_data in r.lrange('history_entity_' + entity, 0, 100):
            data.append(pickle.loads(history_data))

    return HttpResponse(json.dumps(data), mimetype)



#@login_required(login_url=reverse_lazy('login'))
项目:sensu_drive    作者:ilavender    | 项目源码 | 文件源码
def entity_notify_history(request):            

    data = []
    mimetype = 'application/json'   

    if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '':

        entity = request.POST['entity']
        logger.debug("view entity_notify_history user: %s entity: %s" % (request.user.username, entity))

        for history_data in r.lrange('notifyhistory_entity_' + entity, 0, 100):
            data.append(pickle.loads(history_data))

    return HttpResponse(json.dumps(data), mimetype)




#@login_required(login_url=reverse_lazy('login'))
项目:sensu_drive    作者:ilavender    | 项目源码 | 文件源码
def check_config(request):        

    mimetype = 'application/json'   
    data = {}

    if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '':        
        client_name, check_name = request.POST['entity'].split(':')
        #check_name = 'check_gw_tomcat_errors_1h'
        #data = cache.get('check_' + check_name)
        data = cache.get('check_' + request.POST['entity'])


    return HttpResponse(json.dumps(data), mimetype)



#@login_required(login_url=reverse_lazy('login'))
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def change_password(request):
    """
    Sets the new password for user.
    """
    if request.is_ajax():
        change_password_form = ChangePasswordForm(request.POST)

        if change_password_form.is_valid():
            with transaction.atomic():

                if request.user.check_password(change_password_form.cleaned_data['prev_password']):
                    request.user.set_password(change_password_form.cleaned_data['new_password'])
                    request.user.save()

                    logger.info("User '{}' changed his password successfully.".format(request.user))

                    changed_password.delay(request.user.username, request.user.email)

                    return HttpResponse(json.dumps('?????? ??????? ???????!'), content_type='application/json')

                else:
                    return HttpResponse(json.dumps('?????? ?????? ?? ?????????. ????????? ?? ??????? ??????.'),
                                        content_type='application/json')
    else:
        return HttpResponse(status=404)
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def is_user_exists(request):
    """
    Checks if user is exists. If exists return True, else False.
    """
    if request.is_ajax():
        is_user_exists_form = IsUserExistsForm(request.GET)

        if is_user_exists_form.is_valid():
            try:
                User.objects.get(username=is_user_exists_form.cleaned_data['username'])
                return HttpResponse(json.dumps(True), content_type='application/json')

            except ObjectDoesNotExist:
                return HttpResponse(json.dumps(False), content_type='application/json')
    else:
        return HttpResponse(status=404)


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def is_mail_exists(request):
    """
    Checks if mail is exists. If exists return True, else False.
    """
    if request.is_ajax():
        is_mail_exists_form = IsMailExistsForm(request.GET)

        if is_mail_exists_form.is_valid():
            try:
                User.objects.get(email=is_mail_exists_form.cleaned_data['email'])
                return HttpResponse(json.dumps(True), content_type='application/json')

            except ObjectDoesNotExist:
                return HttpResponse(json.dumps(False), content_type='application/json')
    else:
        return HttpResponse(status=404)


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def selected_category(request, category_id):
    """
    Returns page with selected category.
    """
    if request.method == 'GET':
        category = Category.objects.get(id=category_id)
        books = Book.objects.filter(id_category=category).order_by('book_name')

        filtered_books = Book.exclude_private_books(request.user, books)

        context = {'category': category, 'books': filtered_books, 'category_number': category_id}
        return render(request, 'selected_category.html', context)

    else:
        return HttpResponse(status=404)


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def find_books(request):
    """
    Generates list with books of data which user entered. At first it check full equality in name,
    after tries to check if contains some part of entered data.
    """
    if request.is_ajax():
        search_book_form = SearchBookForm(request.GET)

        if search_book_form.is_valid():
            search_data = search_book_form.cleaned_data['data']

            filtered_books = Book.exclude_private_books(request.user, Book.fetch_books(search_data))
            books = Book.generate_books(filtered_books)

            for book in books:
                book['name'] = escape(book['name'])
                book['author'] = escape(book['author'])

            return HttpResponse(json.dumps(books), content_type='application/json')
    else:
        return HttpResponse(status=404)
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def remove_book_from_home(request):
    """
    Removes book from list of user's added books.
    """
    if request.is_ajax():
        book_form = BookHomeForm(request.POST)

        if book_form.is_valid():
            AddedBook.objects.get(id_user=TheUser.objects.get(id_user=request.user),
                                  id_book=Book.objects.get(id=book_form.cleaned_data['book'])).delete()

            logger.info("User '{}' removed book with id: '{}' from his own library."
                        .format(request.user, book_form.cleaned_data['book']))

            return HttpResponse(json.dumps(True), content_type='application/json')
    else:
        return HttpResponse(status=404)


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def change_rating(request):
    if request.is_ajax():
        rating_form = ChangeRatingForm(request.POST)

        if rating_form.is_valid():
            with transaction.atomic():
                set_rating(request, rating_form)

                book_rating = BookRating.objects.filter(id_book=Book.objects.get(id=rating_form.cleaned_data['book']))

                data = {'avg_rating': round(book_rating.aggregate(Avg('rating'))['rating__avg'], 1),
                        'rating_count': '({})'.format(book_rating.count())}

                return HttpResponse(json.dumps(data), content_type='application/json')
    else:
        return HttpResponse(status=404)


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def generate_books(request):
    """
    Returns a list of books.
    """
    if request.is_ajax():
        book_list_form = GenerateBooksForm(request.GET)

        if book_list_form.is_valid():
            list_of_books = Book.generate_existing_books(book_list_form.cleaned_data['part'])

            return HttpResponse(json.dumps(list_of_books), content_type='application/json')

    else:
        return HttpResponse(status=404)


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def set_current_page(request):
    """
    Changes current readed page for book of user.
    """
    if request.is_ajax():
        pages_form = SetCurrentPageForm(request.POST)

        if pages_form.is_valid():
            with transaction.atomic():
                book = Book.objects.get(id=pages_form.cleaned_data['book'])
                user = TheUser.objects.get(id_user=request.user)

                added_book = AddedBook.objects.get(id_book=book, id_user=user)
                added_book.last_page = pages_form.cleaned_data['page']
                added_book.save()

                logger.info("User '{}' on book with id: '{}' changed page to: '{}'."
                            .format(user, book.id, pages_form.cleaned_data['page']))

                return HttpResponse(json.dumps(True), content_type='application/json')
    else:
        return HttpResponse(status=404)
项目:TaleTellers    作者:lyk2017-django    | 项目源码 | 文件源码
def like(request):
    """
    kullan?c? be?endi?inde vya be?enmedi?inde ekrandaki skoru otomatik
    update eder
    """
    id = request.GET.get("id", default=None)
    like = request.GET.get("like")
    obj = get_object_or_404(Post, id=int(id))
    if like == "true":
        # f objesi veri tabanindaki ilgili sutunun degerini cekerek
        # atama yapmak yerine arttirma veya azaltma yapmamizi saglar.
        obj.score = F("score") + 1
        obj.save(update_fields=["score"])
    elif like == "false":
        obj.score = F("score") - 1
        obj.save(update_fields=["score"])
    else:
        return HttpResponse(status=400)
    obj.refresh_from_db()
    return JsonResponse({"like": obj.score, "id": id})
项目:sarafu    作者:pesaply    | 项目源码 | 文件源码
def webhook(request):
    webhook_secret = 'YOUR_WEBHOOK_SECRET_HERE'

    if request.POST.get('secret') != webhook_secret:
        return HttpResponse("Invalid webhook secret", 'text/plain', 403)

    if request.POST.get('event') == 'incoming_message':
        content = request.POST.get('content')
        from_number = request.POST.get('from_number')
        phone_id = request.POST.get('phone_id')

        # do something with the message, e.g. send an autoreply            

        return HttpResponse(json.dumps({
            'messages': [
                {'content': "Thanks for your message!"}
            ]
        }), 'application/json')
项目:MyFirstWebApp    作者:loyal888    | 项目源码 | 文件源码
def Login(request):
 if(request.method == "POST"):
     UserAccount = request.POST.get('name');#?????
     UserPassword = request.POST.get('password');#??????
     userInfo = getUserToSQL(UserAccount,UserPassword);#????? ??????
     if(userInfo):
         if userInfo[0].User_Role == 0:#?????
          request.session['CurrentUserId'] = userInfo[0].User_Id;#????????
          CurrentId = request.session.get('CurrentUserId');
          CurrentUser = getUserToSQLForId(CurrentId)[0];
          objs = UserInfo.objects.filter(User_Role = 1);#????????
          return render(request,'admin.html',{'CurrentUser':CurrentUser,'objs':objs});
         else:#??????
             request.session['CurrentUserId'] = userInfo[0].User_Id;
             CurrentId = request.session.get('CurrentUserId');
             CurrentUser = getUserToSQLForId(CurrentId)[0];
             signStatus = SignStatus.objects.filter(Sign_Status_User=CurrentUser)[0];#??????
             if(signStatus.Sign_Status == True):#????????
                 return render(request, 'normalOne.html', {'CurrentUser': CurrentUser, 'signStatus': signStatus});
             else:#????????

                 return  render(request,'normalTwo.html',{'CurrentUser':CurrentUser,'signStatus':signStatus});
 return HttpResponse("????????????");#?????????

#????
项目:django-tmpl    作者:jarrekk    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        try:
            uid = force_text(urlsafe_base64_decode(kwargs['uid64']))
            user = UserModel.objects.get(pk=uid)
        except Exception as e:
            logger.info(e)
            user = None
        if user is not None and account_activation_token.check_token(user, kwargs['token']):
            email_address = user.emailaddress_set.first()
            email_address.verified = True
            email_address.save()
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            login(request, user)
            # return redirect('home')
            return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
        return HttpResponse('Activation link is invalid!')
项目:Location_Assistance    作者:KamalAwasthi    | 项目源码 | 文件源码
def set_reminder(request):
    current_username = request.POST.get('username')
    current_longitude = request.POST.get('longitude')
    current_latitude = request.POST.get('latitude')
    current_reminder_title = request.POST.get('reminder_title')    
    current_reminder_text = request.POST.get('reminder_text')

    try:
        user=User.objects.get(username=current_username)
    except Exception as e:
        return HttpResponse("username is not registered")

    reminder = Reminder(username = user, longitude = current_longitude, 
        latitude = current_latitude, reminder_title = current_reminder_title, reminder_text = current_reminder_text)
    reminder.save()

    return HttpResponse("reminder has been set")
项目:Location_Assistance    作者:KamalAwasthi    | 项目源码 | 文件源码
def delete_reminder(request):
    current_username = request.POST.get('username')
    reminder_id = request.POST.get('id')

    try:
        user=User.objects.get(username=current_username)
    except Exception as e:
        return HttpResponse("username is not registered")
        #setting = SaveSettings.objects.get(latitude = current_latitude) 
    deleted_reminder = Reminder.objects.get(pk = reminder_id)

    deleted_reminder.delete()

    return HttpResponse("reminder deleted sucessfully")


#Friends Table View
项目:Location_Assistance    作者:KamalAwasthi    | 项目源码 | 文件源码
def delete_friends(request):
    current_username = request.POST.get('username')
    current_friendName = request.POST.get('friendUsername')
    ol=[]
    try:
        existingUser = FriendList.objects.get(user__username = current_username)
        user_friends = existingUser.getfoo()
        for c in user_friends:
            c = unicodedata.normalize('NFKD', c).encode('ascii','ignore')
            if(c == current_friendName):
                continue
            ol.append(c)
        existingUser.friendList = json.dumps(ol)
        existingUser.save()
    except:
        ol=[]
    return HttpResponse(json.dumps(ol))
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def download_annotated(request, individual_id):
    individual = get_object_or_404(Individual, pk=individual_id)

    filepath = os.path.dirname(str(individual.vcf_file.name))
    filename = os.path.basename(str(individual.vcf_file.name))

    # path = settings.MEDIA_ROOT
    # if filename.endswith('vcf.zip'):
       # basename = filename.split('.vcf.zip')[0]       
    # else:

    basename = filename.split('.vcf')[0]

    fullpath = '%s/annotation.final.vcf.zip' % (filepath)

    vcffile = open(fullpath, 'rb')

    response = HttpResponse(vcffile, content_type='application/x-zip-compressed')
    # # response['Content-Encoding'] = 'gzip'
    response['Content-Disposition'] = 'attachment; filename=%s.annotated.mendelmd.vcf.zip' % basename
    response['Content-Length'] = os.path.getsize(fullpath)
    return response
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def export_to_csv(request, variants):
    #export to csv
    export = request.GET.get('export', '')
    if export != '':
        if export == 'csv':
            response = HttpResponse(content_type='text/csv')
            response['Content-Disposition'] = 'attachment; filename=export.csv'
            writer = csv.writer(response)

        elif export == 'txt':
            response = HttpResponse(content_type='text/plain')
            response['Content-Disposition'] = 'attachment; filename=export.txt'
            writer = csv.writer(response, delimiter='\t', quoting=csv.QUOTE_NONE)    
        writer.writerow(['Individual', 'Index', 'Pos_index', 'Chr', 'Pos', 'Variant_id', 'Ref', 'Alt', 'Qual', 'Filter', 'Info', 'Format', 'Genotype_col', 'Genotype', 'Read_depth', 'Gene', 'Mutation_type', 'Vartype', 'Genomes1k_maf', 'Dbsnp_maf', 'Esp_maf', 'Dbsnp_build', 'Sift', 'Sift_pred', 'Polyphen2', 'Polyphen2_pred', 'Condel', 'Condel_pred', 'DANN', 'CADD', 'Is_at_omim', 'Is_at_hgmd', 'Hgmd_entries', 'Effect', 'Impact', 'Func_class', 'Codon_change', 'Aa_change', 'Aa_len', 'Gene_name', 'Biotype', 'Gene_coding', 'Transcript_id', 'Exon_rank', 'Genotype_number', 'Allele', 'Gene', 'Feature', 'Feature_type', 'Consequence', 'Cdna_position', 'Cds_position', 'Protein_position', 'Amino_acids', 'Codons', 'Existing_variation', 'Distance', 'Strand', 'Symbol', 'Symbol_source', 'Sift', 'Polyphen', 'Condel']) 
        for variant in variants:
            # print 'variant', variant.index
            writer.writerow([variant.individual, variant.index, variant.pos_index, variant.chr, variant.pos, variant.variant_id, variant.ref, variant.alt, variant.qual, variant.filter, pickle.loads(variant.info), variant.format, variant.genotype_col, variant.genotype, variant.read_depth, variant.gene, variant.mutation_type, variant.vartype, variant.genomes1k_maf, variant.dbsnp_maf, variant.esp_maf, variant.dbsnp_build, variant.sift, variant.sift_pred, variant.polyphen2, variant.polyphen2_pred, variant.condel, variant.condel_pred, variant.dann, variant.cadd, variant.is_at_omim, variant.is_at_hgmd, variant.hgmd_entries])
        return response
项目:TUMcalendar    作者:ammyg    | 项目源码 | 文件源码
def execute(request):
    p_stud = request.GET.get('pStud', '')
    p_token = request.GET.get('pToken', '')

    if(p_stud == '' or p_token == ''):
        return HttpResponse("error")

    # simple proxy
    # download content from the url
    url = ''.join(["https://campus.tum.de/tumonlinej/ws/termin/ical?pStud=",p_stud,"&pToken=",p_token])
    print(url)
    response = urllib.request.urlopen(url)
    data = response.read()
    #text = data.decode('utf-8')

    return HttpResponse(tumtools.execute(data), content_type="text/calendar")
项目:dj-paypal    作者:HearthSim    | 项目源码 | 文件源码
def post(self, request):
        if "HTTP_PAYPAL_TRANSMISSION_ID" not in request.META:
            # Do not even attempt to process/store the event if there is
            # no paypal transmission id so we avoid overfilling the db.
            return HttpResponseBadRequest()

        trigger = WebhookEventTrigger.from_request(request)

        if trigger.exception:
            # An exception happened, return 500
            return HttpResponseServerError()

        if not trigger.valid:
            # Webhook Event did not validate, return 400
            return HttpResponseBadRequest()

        return HttpResponse(str(trigger.id))
项目:serverthrallapi    作者:NullSoldier    | 项目源码 | 文件源码
def get(self, request, server_id, character_id):
        server = self.get_server(request, server_id)

        if server is None:
            return HttpResponse('server does not exist', status=400)

        character = (Character.objects
            .filter(
                server_id=server.id,
                id=character_id)
            .first())

        if character is None:
            return HttpResponse('character does not exist', status=400)

        histories = CharacterHistory.objects.filter(character_id=character.id)
        serialized = CharacterHistorySerializer(histories, many=True).data
        return JsonResponse({'history': serialized}, status=200)
项目:serverthrallapi    作者:NullSoldier    | 项目源码 | 文件源码
def get(self, request, server_id, character_id):
        server = self.get_server(request, server_id)

        if server is None:
            return HttpResponse('server does not exist', status=400)

        character = (Character.objects
            .filter(
                server_id=server.id,
                id=character_id)
            .first())

        if character is None:
            return HttpResponse('character does not exist', status=400)

        serialized = CharacterSerializer(character).data
        return JsonResponse(serialized, status=200)
项目:serverthrallapi    作者:NullSoldier    | 项目源码 | 文件源码
def post(self, request, server_id):
        if 'private_secret' not in request.GET:
            return HttpResponse('missing required param private_secret', status=400)

        server = (Server.objects
            .filter(id=server_id, private_secret=request.GET['private_secret'])
            .first())

        if server is None:
            return HttpResponse('server does not exist', status=404)

        data = json.loads(request.body)

        if 'characters' in data:
            sync_characters_task.delay(server.id, data['characters'], request.GET)

        if 'clans' in data:
            sync_clans_task.delay(server.id, data['clans'])

        server.last_sync = timezone.now()
        server.save()

        delete_old_history.delay()
        return HttpResponse(status=200)
项目:serverthrallapi    作者:NullSoldier    | 项目源码 | 文件源码
def post(self, request, server_id):
        if 'private_secret' not in request.GET:
            return HttpResponse('missing required param private_secret')

        data = request.GET
        server = self.get_server(request, server_id)

        if server is None:
            return HttpResponse('server does not exist', status=404)

        if 'name' in data:
            server.name = data['name']

        server.save()

        serialized = ServerAdminSerializer(server).data
        return JsonResponse(serialized, status=200)
项目:serverthrallapi    作者:NullSoldier    | 项目源码 | 文件源码
def get(self, request, server_id, clan_id):
        server = self.get_server(request, server_id)

        if server is None:
            return HttpResponse('server does not exist', status=400)

        clan = (Clan.objects
            .filter(
                server_id=server.id,
                id=clan_id)
            .first())

        if clan is None:
            return HttpResponse('clan does not exist', status=400)

        serialized = ClanSerializer(clan).data
        return JsonResponse(serialized, status=200)
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def test_instance_log(self):
        server = self.servers.first()
        CONSOLE_OUTPUT = 'output'

        api.nova.server_console_output(IsA(http.HttpRequest),
                                       server.id, tail_length=None) \
            .AndReturn(CONSOLE_OUTPUT)

        self.mox.ReplayAll()

        url = reverse('horizon:project:instances:console',
                      args=[server.id])
        tg = tabs.InstanceDetailTabs(self.request, instance=server)
        qs = "?%s=%s" % (tg.param_name, tg.get_tab("log").get_id())
        res = self.client.get(url + qs)

        self.assertNoMessages()
        self.assertIsInstance(res, http.HttpResponse)
        self.assertContains(res, CONSOLE_OUTPUT)
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def get(self, request, keypair_name=None, optional=None):
        try:
            if optional == "regenerate":
                api.nova.keypair_delete(request, keypair_name)

            keypair = api.nova.keypair_create(request, keypair_name)
        except Exception:
            redirect = reverse('horizon:project:access_and_security:index')
            exceptions.handle(self.request,
                              _('Unable to create key pair: %(exc)s'),
                              redirect=redirect)

        response = http.HttpResponse(content_type='application/binary')
        response['Content-Disposition'] = ('attachment; filename=%s.pem'
                                           % slugify(keypair.name))
        response.write(keypair.private_key)
        response['Content-Length'] = str(len(response.content))
        return response
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def test_wrap_list_rendering(self):
        self.table = MyTableWrapList(self.request, TEST_DATA_7)
        row = self.table.get_rows()[0]
        name_cell = row.cells['name']
        value_cell = row.cells['value']
        optional_cell = row.cells['optional']

        # Check if is cell is rendered correctly.
        name_cell_rendered = name_cell.render()
        value_cell_rendered = value_cell.render()
        optional_cell_rendered = optional_cell.render()
        resp_name = http.HttpResponse(name_cell_rendered)
        resp_value = http.HttpResponse(value_cell_rendered)
        resp_optional = http.HttpResponse(optional_cell_rendered)
        self.assertContains(resp_name, '<ul>wrapped name</ul>', 1)
        self.assertContains(resp_value, '<ul>wrapped value</ul>', 1)
        self.assertContains(resp_optional, 'not wrapped optional', 1)
        self.assertNotContains(resp_optional, '<ul>')
        self.assertNotContains(resp_optional, '</ul>')
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def test_inline_edit_available_cell_rendering(self):
        self.table = MyTable(self.request, TEST_DATA_2)
        row = self.table.get_rows()[0]
        name_cell = row.cells['name']

        # Check if in-line edit is available in the cell,
        # but is not in inline_edit_mod.
        self.assertTrue(name_cell.inline_edit_available)
        self.assertFalse(name_cell.inline_edit_mod)

        # Check if is cell is rendered correctly.
        name_cell_rendered = name_cell.render()
        resp = http.HttpResponse(name_cell_rendered)

        self.assertContains(resp, '<td', 1)
        self.assertContains(resp, 'inline_edit_available', 1)
        self.assertContains(resp,
                            'data-update-url="?action=cell_update&amp;'
                            'table=my_table&amp;cell_name=name&amp;obj_id=1"',
                            1)
        self.assertContains(resp, 'table_cell_wrapper', 1)
        self.assertContains(resp, 'table_cell_data_wrapper', 1)
        self.assertContains(resp, 'table_cell_action', 1)
        self.assertContains(resp, 'ajax-inline-edit', 1)
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def test_inline_edit_available_not_allowed_cell_rendering(self):
        self.table = MyTableNotAllowedInlineEdit(self.request, TEST_DATA_2)

        row = self.table.get_rows()[0]
        name_cell = row.cells['name']

        # Check if in-line edit is available in the cell,
        # but is not in inline_edit_mod.
        self.assertTrue(name_cell.inline_edit_available)
        self.assertFalse(name_cell.inline_edit_mod)

        # Check if is cell is rendered correctly.
        name_cell_rendered = name_cell.render()
        resp = http.HttpResponse(name_cell_rendered)

        self.assertContains(resp, '<td', 1)
        self.assertContains(resp, 'inline_edit_available', 1)
        self.assertContains(resp,
                            'data-update-url="?action=cell_update&amp;'
                            'table=my_table&amp;cell_name=name&amp;obj_id=1"',
                            1)
        self.assertContains(resp, 'table_cell_wrapper', 0)
        self.assertContains(resp, 'table_cell_data_wrapper', 0)
        self.assertContains(resp, 'table_cell_action', 0)
        self.assertContains(resp, 'ajax-inline-edit', 0)
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def test_table_action_attributes(self):
        table = MyTable(self.request, TEST_DATA)
        self.assertTrue(table.has_actions)
        self.assertTrue(table.needs_form_wrapper)
        res = http.HttpResponse(table.render())
        self.assertContains(res, "<form")

        table = MyTable(self.request, TEST_DATA, needs_form_wrapper=False)
        self.assertTrue(table.has_actions)
        self.assertFalse(table.needs_form_wrapper)
        res = http.HttpResponse(table.render())
        self.assertNotContains(res, "<form")

        table = NoActionsTable(self.request, TEST_DATA)
        self.assertFalse(table.has_actions)
        self.assertFalse(table.needs_form_wrapper)
        res = http.HttpResponse(table.render())
        self.assertNotContains(res, "<form")
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
def serve(self, request, file_obj, **kwargs):
        fullpath = file_obj.path
        # the following code is largely borrowed from `django.views.static.serve`
        # and django-filetransfers: filetransfers.backends.default
        if not os.path.exists(fullpath):
            raise Http404('"%s" does not exist' % fullpath)
        # Respect the If-Modified-Since header.
        statobj = os.stat(fullpath)

        content_type_key = 'mimetype' if LTE_DJANGO_1_4 else 'content_type'
        response_params = {content_type_key: self.get_mimetype(fullpath)}
        if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                                  statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
            return HttpResponseNotModified(**response_params)
        response = HttpResponse(open(fullpath, 'rb').read(), **response_params)
        response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
        self.default_headers(request=request, response=response, file_obj=file_obj, **kwargs)
        return response
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def host_meta_view(request):
    """Generate a `.well-known/host-meta` document"""
    host_meta = generate_host_meta("diaspora", webfinger_host=settings.SOCIALHOME_URL)
    return HttpResponse(host_meta, content_type="application/xrd+xml")