【问题标题】:Django XML on RequestDjango XML 请求
【发布时间】:2011-05-20 13:06:11
【问题描述】:

我有问题

在我的views.py中,我有一个从POST中获取xml并做一些事情的方法。

def check_xml(request):
    try:
        # get the XML records from the POST data
        xml = request.raw_post_data

效果很好,我可以使用以下方法对其进行测试:

xml_data = """<root><a><b>Hello</b><\a></root>""" 
h = Http()
resp, content = h.request("http://myurl/check_xml", "POST", xml_data)

但是,在我看来,我还有另一个函数,我想调用 check_xml()

# i construct some xml using lxml.etree
myrequest.raw_post_data = new_xml
check_xml(myrequest)

我宁愿不必调用 url,因为我在视图中调用了另一个方法。

【问题讨论】:

  • 如果我理解正确,您想通过views.py 中的另一个方法调用check_xml(),而不必向http://myurl/check_xml 发送请求?
  • 是的。也许我应该有第二个可选参数 def check_xml(request, xml=None)

标签: django django-views


【解决方案1】:

提取check_xml() 中操作XML 对象的部分,以独立于请求对象的自己的方法:

def xml_function(xml):
  #do what you have to do with the `xml` arg
  ...

check_xml() 和任何其他方法(直接调用(无请求))中调用它。

def check_xml(request):
    try:
        # get the XML records from the POST data
        xml = request.raw_post_data
        ...
        xml_function(xml)
        ...

def other_function():
    ...
    xml_function(new_xml)
    ...

【讨论】:

  • @Mark,在这里设置 manji 的回复作为答案。这让您在同一条船上的其他 StackOverflow 用户知道这里有一个经过验证的答案。
猜你喜欢
  • 1970-01-01
  • 2010-12-21
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 2013-02-15
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多