如何使用填充的META字段创建Django HttpRequest对象? [英] How do you create a Django HttpRequest object with the META fields populated?

查看:87
本文介绍了如何使用填充的META字段创建Django HttpRequest对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Django中创建具有所有 cgi <$ c $的 HttpRequest 对象的方法c> META 变量存在吗?我正在尝试处理视图,但无法弄清楚如何(轻松)制作请求对象。我只想确保自己的工作不会比手动复制现有请求中的所有字段困难。 感觉就像是已经存在的解决方案,但是经过几个小时的搜索,我找不到我需要的东西。

Is there a way to create an HttpRequest object in Django that has all of the cgi META variables present? I'm attempting to process a view, but can't figure out how to (easily) make the request object. I just want to make sure I'm not making life harder than need be manually copying all the fields from an existing request. This feels like something there'd be an existing solution for, but after several hours of searching, I can't find what I need.

我最初与 Client RequestFactory 来自 django.test ,但是它们用垃圾数据填充了请求对象,这会使我视图中的某些动态字段呈现不正确的值(例如,诸如 SERVER_NAME 之类的东西)

I originally went with Client and RequestFactory from django.test, but these fill the request object with junk data, which causes some of the dynamic fields in my view to render with incorrect values (for example, things like SERVER_NAME)

是否有正确的方法来创建可用的HttpRequest对象?

Is there a correct way to create a usable HttpRequest object?

推荐答案

首先,我只想澄清一下您的问题:

First, I just want to clarify a couple things in your question:


我正在尝试处理视图

I'm attempting to process a view

通过处理视图,我以为您的意思是您想将HttpRequest对象传递到视图的函数中。通常,这是通过 URL分配器完成的。

By "process a view", I think you mean that you want to pass an HttpRequest object into your view's functions. This is usually done through a URL dispatcher.


我只想确保自己的工作不会比手动复制现有请求中的所有字段困难。

I just want to make sure I'm not making life harder than need be manually copying all the fields from an existing request.

听起来您想基于现有请求创建一个新的HttpRequest对象,尤其是不要弄乱标题。您应该查看 django.http.HttpRequest 文档以重新使用现有请求字段中的某些字段。例如, request.META 是可以在请求对象之间重复使用的字典。

It sounds like you want to create a new HttpRequest object based on an existing request, particularly without messing with the headers. You should look over the django.http.HttpRequest documentation to re-use some of the fields from your existing request's fields. For example, request.META is a dictionary that can be re-used between request objects.

似乎最好的方法是直接使用django.http.HttpRequest对象。您可以如下创建它:

It seems like your best approach is to use the django.http.HttpRequest object directly. You can create it as follows:

from django.http import HttpRequest
request = HttpRequest()

然后,您可以根据需要设置字段,并只是一个空字典,您可以随意设置。例如:

Then you can set the fields however you like, and request.META is just an empty dictionary that you can set however you like. For example:

request.method = 'GET'
request.META = myOldRequest.META
request.META['SERVER_NAME'] = 'localhost'

我可以让您查找其余部分。希望有帮助!

I can let you look up the rest. Hopefully that helps!

这篇关于如何使用填充的META字段创建Django HttpRequest对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆