相关疑难解决方法(0)

从URL读取.csv文件到Python 3.x - _csv.Error:迭代器应该返回字符串,而不是字节(你是否在文本模式下打开文件?)

我一直在努力解决这个简单的问题,所以我想我会寻求帮助.我正在尝试将国家医学图书馆ftp站点的期刊文章列表读入Python 3.3.2(在Windows 7上).期刊文章位于.csv文件中.

我试过以下代码:

import csv
import urllib.request

url = "ftp://ftp.ncbi.nlm.nih.gov/pub/pmc/file_list.csv"
ftpstream = urllib.request.urlopen(url)
csvfile = csv.reader(ftpstream)
data = [row for row in csvfile]
Run Code Online (Sandbox Code Playgroud)

它会导致以下错误:

Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
data = [row for row in csvfile]
File "<pyshell#4>", line 1, in <listcomp>
data = [row for row in csvfile]
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
Run Code Online (Sandbox Code Playgroud)

我认为我应该使用字符串而不是字节?任何有关简单问题的帮助,以及对出现问题的解释都将非常感激.

python csv url python-3.x

30
推荐指数
2
解决办法
3万
查看次数

在Python中获取HTTP响应的字符集/编码的好方法

寻找一种使用Python urllib2或任何其他Python库获取HTTP响应的字符集/编码信息的简单方法.

>>> url = 'http://some.url.value'
>>> request = urllib2.Request(url)
>>> conn = urllib2.urlopen(request)
>>> response_encoding = ?
Run Code Online (Sandbox Code Playgroud)

我知道它有时出现在'Content-Type'标题中,但该标题有其他信息,并且它嵌入在我需要解析的字符串中.例如,Google返回的Content-Type标头是

>>> conn.headers.getheader('content-type')
'text/html; charset=utf-8'
Run Code Online (Sandbox Code Playgroud)

我可以使用它,但我不确定格式的一致性.我很确定charset可能完全丢失,所以我必须处理这个边缘情况.某种类型的字符串拆分操作使得"utf-8"从中看出来似乎是做错这种事情的错误方法.

>>> content_type_header = conn.headers.getheader('content-type')
>>> if '=' in content_type_header:
>>>  charset = content_type_header.split('=')[1]
Run Code Online (Sandbox Code Playgroud)

这种代码感觉就像做了太多的工作.我也不确定它是否适用于所有情况.有没有人有更好的方法来做到这一点?

python urllib2 httprequest character-encoding

26
推荐指数
3
解决办法
4万
查看次数

HTTPResponse对象 - JSON对象必须是str,而不是'bytes'

我一直在尝试更新一个名为libpynexmo的小型Python库来使用Python 3.

我一直坚持这个功能:

def send_request_json(self, request):
    url = request
    req =  urllib.request.Request(url=url)
    req.add_header('Accept', 'application/json')
    try:
        return json.load(urllib.request.urlopen(req))
    except ValueError:
        return False
Run Code Online (Sandbox Code Playgroud)

当它到达时,json回应:

TypeError: the JSON object must be str, not 'bytes'
Run Code Online (Sandbox Code Playgroud)

我在几个地方读到,json.load你应该传递HTTPResponse带有.read()附件的对象(在这种情况下是一个对象),但它不适用于HTTPResponse对象.

我不知道下一步该怎么做,但由于我的整个1500行脚本刚刚转换为Python 3,我不想回到2.7.

json python-3.x nexmo python-3.4

26
推荐指数
3
解决办法
6万
查看次数

如何将集成测试(而不是单元测试)应用于Flask RESTful API

[根据/sf/answers/3245896181/,标题应参考集成测试而不是单元测试]

假设我想测试以下Flask API(从这里开始):

import flask
import flask_restful

app = flask.Flask(__name__)
api = flask_restful.Api(app)

class HelloWorld(flask_restful.Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

if __name__ == "__main__":
    app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)

将此保存flaskapi.py并运行后,在同一目录中运行脚本test_flaskapi.py:

import unittest
import flaskapi
import requests

class TestFlaskApiUsingRequests(unittest.TestCase):
    def test_hello_world(self):
        response = requests.get('http://localhost:5000')
        self.assertEqual(response.json(), {'hello': 'world'})


class TestFlaskApi(unittest.TestCase):
    def setUp(self):
        self.app = flaskapi.app.test_client()

    def test_hello_world(self):
        response = self.app.get('/')

if __name__ == "__main__":
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

两个测试都通过了,但对于第二个测试(在TestFlaskApi类中定义),我还没有弄清楚如何断言JSON响应是否符合预期(即{'hello': 'world'}).这是因为它是一个实例flask.wrappers.Response(可能基本上是一个Werkzeug响应对象(参见http://werkzeug.pocoo.org/docs/0.11/wrappers/)),但我找不到相应的Response …

python integration-testing werkzeug flask flask-restful

22
推荐指数
3
解决办法
3万
查看次数

charset参数可以与http/1.1中的application/json内容类型一起使用吗?

例如,它是有效的ajax请求:

$.ajax({
    type: "POST",
    url: "SomePage.aspx/GetSomeObjects",
    contentType: "application/json; charset=utf-8",
    ...
});
Run Code Online (Sandbox Code Playgroud)

有时用作示例,或者软件可以在没有显式字符集的情况下中断.

应用程序/ json媒体类型的rfc 4627表示它不接受第6节中的任何参数:

The MIME media type for JSON text is application/json.

Type name: application

Subtype name: json

Required parameters: n/a

Optional parameters: n/a
Run Code Online (Sandbox Code Playgroud)

可以解释为charset不应该与application/json一起使用.

第3节表明,这是没有必要指定字符集:

JSON text SHALL be encoded in Unicode.  The default encoding is
UTF-8.

Since the first two characters of a JSON text will always be ASCII
characters [RFC0020], it is possible to determine whether …
Run Code Online (Sandbox Code Playgroud)

json http character-encoding

13
推荐指数
2
解决办法
7987
查看次数

json.loads 的 Python3 奇怪错误

我在使用服务 api 生成 JSON 响应的 Web 应用程序中使用。该函数的以下部分工作正常并返回 JSON 文本输出:

def get_weather(query = 'london'):
    api_url = "http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=XXXXX****2a6eaf86760c"
    query = urllib.request.quote(query)
    url = api_url.format(query)
    response = urllib.request.urlopen(url)
    data = response.read()    
    return data
Run Code Online (Sandbox Code Playgroud)

返回的输出是:

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"cmc stations","main":{"temp":12.95,"pressure":1030,"humidity":68,"temp_min":12.95,"temp_max":12.95,"sea_level":1039.93,"grnd_level":1030},"wind":{"speed":5.11,"deg":279.006},"clouds":{"all":76},"dt":1462290955,"sys":{"message":0.0048,"country":"GB","sunrise":1462249610,"sunset":1462303729},"id":2643743,"name":"London","cod":200}
Run Code Online (Sandbox Code Playgroud)

这意味着这data是一个字符串,不是吗?

但是,评论return data然后添加以下两行:

jsonData = json.loads(data)
return jsonData
Run Code Online (Sandbox Code Playgroud)

产生以下错误:

类型错误:JSON 对象必须是 str,而不是 'bytes'

怎么了?dataJSON 对象,以前作为字符串返回!我需要知道错误在哪里?

python json flask python-3.x

1
推荐指数
1
解决办法
9434
查看次数

Python:从 JSON 响应的部分构建 DataFrame

我正在尝试开发一个应用程序来检索股票价格(以 JSON 格式),然后对其进行一些分析。我的问题是将 JSON 响应放入我可以工作的 pandas DataFrame 中。这是我的代码:

'''
References
http://stackoverflow.com/questions/6862770/python-3-let-json-object-  accept-bytes-or-let-urlopen-output-strings
'''
import json
import pandas as pd
from urllib.request import urlopen

#set API call
url = "https://www.quandl.com/api/v3/datasets/WIKI/AAPL.json?start_date=2017-01-01&end_date=2017-01-31"

#make call and receive response
response = urlopen(url).read().decode('utf8')
dataresponse = json.loads(response)

#check incoming
#print(dataresponse)

df = pd.read_json(dataresponse)

print(df)
Run Code Online (Sandbox Code Playgroud)

应用程序出现df = pd.read_json...错误TypeError: Expected String or Unicode

所以我认为这是第一个障碍。

第二是到达我需要去的地方。JSON 响应仅包含两个我感兴趣的数组,column_namesdata。如何仅提取这两个并将其放入 pandas DataFrame 中?

json dataframe python-3.x pandas

1
推荐指数
1
解决办法
2301
查看次数