免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1865 | 回复: 0
打印 上一主题 下一主题

Getting Basecamp API Working with Python [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-04-05 19:57 |只看该作者 |倒序浏览

I found
one library that was linked everywhere
, but it wasn’t working for me. I was always getting 400 Bad Request when using it. Chris Conover was able to get the following code working.
import urllib2

protocol = 'https://'
url = 'example.com'
command = '/projects.xml'
headers = {'Accept' : 'application/xml',
'Content-type' : 'applications/xml'}
username = 'x'
password = 'y'

# Setup password stuff
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)

# Send the request and get response
req = urllib2.Request(protocol + url + command, None, headers)
response = urllib2.urlopen(req)
results = response.read()

print results
I thought it was a problem with how the authorization was formed so based on the above code I modified the old basecamp.py file and I was able to get a response. The following is what I changed.
Around line 64
    def __init__(self, username, password, protocol, url):
        self.baseURL = protocol+url
        if self.baseURL[-1] == '/':
            self.baseURL = self.baseURL[:-1]

        passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
        passman.add_password(None, url, username, password)
        authhandler = urllib2.HTTPBasicAuthHandler(passman)

        self.opener = urllib2.build_opener(authhandler)
And around line 142
path = '/projects.xml'
With that I was able to use basecamp.py to retrieve a list of projects. Other modifications may be needed for other features, but that was all I planned on using.
Here is an example of using
ElementTree
to parse the XML response to get the names of all of the projects returned from basecamp.
import elementtree.ElementTree as ET
from basecamp import Basecamp

protocol = 'https://'
url = 'example.com'
username = 'x'
password = 'y'

bc = Basecamp(username, password, protocol, url)
projects = bc.projects()
tree = ET.fromstring(projects)
tags = tree.getiterator(tag='project')

for t in tags:
    project_name = t.findtext('name')


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/78/showart_1890693.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP