我需要从API中提取一些数据。它以XML格式返回GET,我在尝试弄清楚如何将API中的一些数据分配给django / python中模型中的字段时遇到了一些问题。
activeCollab的API不允许我创建自己的projectID号,它会自动为我生成号码。所以我想取这个数字,然后将它分配给我的项目模型中的API_id字段。有人可以帮我弄清楚如何获取GET返回的XML并将其分配给我的一个字段。
项目的ActiveCollab API文档: http://www.activecollab.com/docs/manuals/developers/api/projects
这是我的models.py
class Project(models.Model):
client = models.ForeignKey(Clients, related_name='projects')
created_by = models.ForeignKey(User, related_name='created_by')
#general information
API_id = models.IntegerField(max_length=10, verbose_name='aC ProjectID', null=True, blank=True)
proj_name = models.CharField(max_length=255, verbose_name='Project Name')
pre_quote = models.CharField(max_length=3)
quote = models.IntegerField(max_length=10, verbose_name='Quote #', unique=True)
estimator = models.ForeignKey(User, related_name='Estimator', null=True)
desc = models.TextField(verbose_name='Description', null=True, blank=True)
starts_on = models.DateField(verbose_name='Start Date')
due_date = models.DateField(verbose_name='Due Date', null=True, blank=True)
completed_on = models.DateField(verbose_name='Finished On', null=True, blank=True)
notes = models.TextField(verbose_name='Notes', null=True, blank=True)
Views.py
def addProject(request):
if request.method == 'POST':
form = AddSingleProjectForm(request.POST)
if form.is_valid():
project = form.save(commit=False)
project.created_by = request.user
today = datetime.date.today()
project.pre_quote = "%s-" % (str(today.year)[2:4])
project.quote = Project.objects.latest().quote+1
project.save()
project.status.create(
value = form.cleaned_data.get('status', None)
)
#API activeCollab
params = urllib.urlencode({
'format':'xml',
'submitted':'submitted',
'project[name]': project.proj_name,
'project[overview]': project.desc,
'project[starts_on]': project.starts_on,
'project[leader_id]': 10,
})
req = urllib2.Request("web_url/public/api.php?path_info=/projects/add&token=####################", params)
f = urllib2.urlopen(req)
print f.read()
return HttpResponseRedirect('/project/')
else:
form = AddSingleProjectForm()
return render_to_response('project/addProject.html', {
'form': form, 'user':request.user}, context_instance=RequestContext(request))
任何建议都将受到赞赏。
史蒂夫
聚苯乙烯。我展示的api调用是创建一个新项目
答案 0 :(得分:1)
看了你发布的链接...这样的事情可能会让你开始使用lxml
和xpath
:
>>> from lxml import etree
>>> doc = etree.XML("""<projects>
... <project>
... <id>1</id>
... <name>
... <![CDATA[First Project]]>
... </name>
... <overview>
... <![CDATA[<p>This is overview of the first project</p>]]>
... </overview>
... <status>
... <![CDATA[active]]>
... </status>
... <type>...</type>
... <permalink>...</permalink>
... <leader_id>...</leader_id>
... <company_id>...</company_id>
... <group_id>...</group_id>
... </project>
... </projects>""")
>>> data = {}
>>> for a in doc.xpath('/projects/project/*'):
... data[a.tag] = str(a.text).strip()
...
>>> data
{'company_id': '...',
'group_id': '...',
'id': '1',
'leader_id': '...',
'name': 'First Project',
'overview': '<p>This is overview of the first project</p>',
'permalink': '...',
'status': 'active',
'type': '...'}
<强>更新强>
稍微明确的帮助:
假设您的文件中有from lxml import etree
。这是您的addProject
功能的片段:
req = urllib2.Request("web_url/public/api.php?path_info=/projects/add&token=####################", params)
resp = urllib2.urlopen(req)
resp_data = f.read()
if not resp.code == 200 and resp.headers.get('content-type') == 'text/xml':
# Do your error handling.
raise Exception('Unexpected response',req,resp)
data = etree.XML(resp_data)
api_id = int(data.xpath('/project/id/text()')[0])
project.API_id = api_id
project.save()