如何使用python3通过SSL进行BasicAuth REST查询

时间:2015-03-13 18:45:14

标签: python-3.x afnetworking urllib

我有一个龙卷风服务器,充当iPhone应用程序的REST界面。我想使用python程序对所述服务器进行一些查询。在iOS方面,我使用AFNetworking库。但我不知道python客户端上的类比是什么。

我的ObjectiveC / AFNetworking代码如下所示:

+ (HttpConnection*) current {
    static HttpConnection* current = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        current = [[self alloc] initWithBaseURL: [NSURL URLWithString: BaseURL]];
        current.securityPolicy.allowInvalidCertificates = YES;
        current.responseSerializer = [AFJSONResponseSerializer serializer];
        current.requestSerializer = [AFJSONRequestSerializer serializer];
    });
    [current.requestSerializer setAuthorizationHeaderFieldWithUsername: Username password: Password];
    return current;
}

- (void)pull: (NSString*)resource fields: (NSArray*)fields then: (void(^)())block {
    //  NSLog(@"%@ pulling...", self);
    NSString* uri = [NSString stringWithFormat: @"%@/%@", [self rootREST], self.serialID];
    if (resource) {
        uri = [NSString stringWithFormat: @"%@/%@", uri, resource];
    }
    [[HttpConnection current]
        GET: uri
        parameters: fields ? @{@"fields": fields} : nil
        success:^(NSURLSessionDataTask* task, id responseObject){
            [self performSelectorOnMainThread: @selector(fromDoc:) withObject:responseObject waitUntilDone:YES];
            if (block) block();
        }
        failure:^(NSURLSessionDataTask* task, NSError* error){
            NSLog(@"%@ pull error: %@ (uri=%@)", self, error, uri);
        }
    ];
}

所以我正在寻找的功能是:

  1. 使用类似https://a.b.c:7895/
  2. 的BaseURL进行初始化
  3. 添加resource/path
  4. 允许无效(自签名)证书
  5. 设置BasicAuth标题
  6. 向查询添加其他参数
  7. 运行GET请求
  8. 我是否使用urllib来完成所有这些操作?或者我需要使用不同的东西。我想要一个如何做到这一点的例子。

1 个答案:

答案 0 :(得分:1)

我强烈推荐python请求库(我做了检查,它确实支持python 3.x)。它应该简单:

import requests
username = "SomeUser"
password = "SomePass"
r = requests.get("https://a.b.c:7895/resource/path?param1=foo",auth=(username,password),verify=False)