gpt4 book ai didi

raku - Perl 6 中的 urlopen 方法?

转载 作者:行者123 更新时间:2023-12-04 15:06:54 25 4
gpt4 key购买 nike

我正在将 Python 模块转换为 Perl 6,但找不到名为 urlopen 的方法, 可以接受 数据 :

    from six.moves.urllib import request

req = request.Request(url, headers=headers)

if headers.get('Content-Type') == 'application/x-www-form-urlencoded':
data = oauth_query(args, via='quote_plus', safe='').encode()

elif 'form-data' in headers.get('Content-Type', ''): # multipart/form-data
data = args['form-data']
else:
data = None

resp = request.urlopen(req, data=data)
resp.json = lambda: json.loads(resp.read().decode() or '""')
return resp
oauth_query是一个返回排序字符串的方法:
def oauth_query(args, via='quote', safe='~'):
return '&'.join('%s=%s' % (k, oauth_escape(v, via, safe)) for k, v in sorted(args.items()))

我将上面的代码翻译成 Perl 6:
   use WWW;

my $data = "";
if %headers{'Content-Type'} eq 'application/x-www-form-urlencoded' {
$data = oauth_query(%args);
} elsif %headers{'Content-Type'}.contains('form-data') {
$data = %args{'form-data'};
} else {
$data = Any;
}

my $res = get $url, |%headers; # but without data that contains Content-Type, it will
# Died with HTTP::MediaType::X::MediaTypeParser::IllegalMediaType

我想返回 resp就像在 Python 中一样。欢迎任何帮助!

最佳答案

use Cro::HTTP::Client;

my $resp;
my $data = "";

if (%headers{'content-type'} // '') eq self.form_urlencoded {
$data = oauth_query(%args);
} elsif (%headers{'content-type'} // '').contains('form-data') { # multipart/form-data
$data = %args{'form-data'};
} else {
$data = "";
}

my $client = Cro::HTTP::Client.new(headers => |%headers);

if $data {
$resp = await $client.post: $url, body => |%args;
} else {
$resp = await $client.get: $url;
}

return $resp;

关于raku - Perl 6 中的 urlopen 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49690676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com