Django:如何访问中间件类中的URL regex参数? [英] Django: How to access URL regex parameters inside a middleware class?

查看:148
本文介绍了Django:如何访问中间件类中的URL regex参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Google App Engine上进行Django项目。我有一个URL:



http:// localhost:8080 / [company] / projects / project / p>

请注意, [company] 是在我的urls.py中定义的一个URL参数,如:



(r'(^ [a-zA-Z0-9 -_。] *)/ projects / project /(\d *)','projects。我想要获得 [公司]的价值

>从我将GAE数据存储命名空间设置为 [company] 值的中间件。



是否可以从 [company] 参数> process_request 中间件类的方法

解决方案

如果您使用 process_view 中间件,您将可以访问视图参数,因此可以访问公司的价值。看看函数的定义:

  def process_view(self,request,view_func,view_args,view_kwargs)
。 ..




view_args是将被传递给的位置参数列表视图和view_kwargs是将被传递给视图的关键字参数的字典。


所以你应该能够抓住它从那里,像:

  def process_view(self,request,view_func,view_args,view_kwargs):
company = view_kwargs.get('company',None)

以下是django书中有关如何您的urls中的命名组和未命名组在您的视图中转换为args和kwargs:



http://www.djangobook.com/en/1.0/chapter08/#cn38



特别


这个[命名的url组]完成了与上一个例子完全相同的事情,有一个微妙的区别:捕获的值被传递给查看函数作为关键字参数,而不是位置参数。



I am working on a Django project on Google App Engine. I have a URL like:

http://localhost:8080/[company]/projects/project

Note that [company] is a URL parameter defined in my urls.py like:

(r'(^[a-zA-Z0-9-_.]*)/projects/project/(\d*)', 'projects.views.project_form'),

I want to get the value of [company] from a middleware where I will set the GAE datastore namespace to the [company] value.

Is it possible to get the [company] parameter from the request object passed in the process_request method of middleware class?

解决方案

If you are using the process_view middleware, you will have access to the views arguments and therefore the company value. Have a look at the function's definition:

def process_view(self, request, view_func, view_args, view_kwargs)
    ...

view_args is a list of positional arguments that will be passed to the view, and view_kwargs is a dictionary of keyword arguments that will be passed to the view.

so you should just be able to grab it from there, something like:

def process_view(self, request, view_func, view_args, view_kwargs):
    company = view_kwargs.get('company', None)

Here's some more info from the django book on how the named and unnamed groups in your urls translate to args and kwargs in your view:

http://www.djangobook.com/en/1.0/chapter08/#cn38

particularly

This [named url groups] accomplishes exactly the same thing as the previous example, with one subtle difference: the captured values are passed to view functions as keyword arguments rather than positional arguments.

这篇关于Django:如何访问中间件类中的URL regex参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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