我有一个用Python3编写的简单Web服务器(使用类http.server),我将从2移植到3.
我有以下代码:
# More code here...
postvars = cgi.parse_qs(self.rfile.read(length),
keep_blank_values=1)
something.json_run(json.dumps(postvars))
Run Code Online (Sandbox Code Playgroud)
哪个投掷:
TypeError: keys must be a string
Run Code Online (Sandbox Code Playgroud)
通过检查数据,我已经确定parse_qs似乎将密钥编码为字节,这就是抛出错误(json显然不喜欢字节).
import json
json.dumps({b'Throws error' : [b"Keys must be a string"]})
json.dumps({'Also throws error': [b'TypeError, is not JSON serializable']})
json.dumps({'This works': ['No bytes!']})
Run Code Online (Sandbox Code Playgroud)
这里最好的解决方案是什么?使用Python 2,代码工作正常,因为parse_qs使用str而不是bytes.我最初的想法是我可能需要编写一个JSON序列化程序.并不是说这么简单的事情很困难,但我不愿意,如果我能用其他方式做到这一点(例如将字典翻译为使用字符串而不是字节).
我正在使用Python和unittest模块进行TDD .在NUnit中你可以Assert.Inconclusive("This test hasn't been written yet").
到目前为止,我还没有在Python中找到类似的东西来表示"这些测试只是占位符,我需要回来并实际将代码放入其中."
这是否有Pythonic模式?
我正在使用Flask与Flask-WTForms,我正在编写一个管理页面,可以更新用户的值 - 包括密码.
我正在使用我用于注册的相同表单页面,但由于不必更新密码,我不想要它.使用Flask-WTForms进行此操作的正确方法是什么?
我已经进入UserForm了forms.py,我正在考虑制作一个自定义验证器,并且有一个文件级require_password选项可以覆盖默认检查.我是WTForms的新手,对Flask来说有点新鲜.
我试图使用子进程调用Vim,并传递一个参数.例如:
subprocess.call(['gvim.exe', ''' "+map <F5> :echo 'Hello!'<cr>" '''])
Run Code Online (Sandbox Code Playgroud)
此命令适用于命令行:
> gvim.exe "+map <F5> :echo 'Hello!'<cr>"
Run Code Online (Sandbox Code Playgroud)
然后我打了F5它,它告诉我你好.
子进程调用不起作用.当我在任务管理器中查看进程时,我看到我的字符串现在是:
"\" +map <F5> :echo 'Hello!'<cr>\""
Run Code Online (Sandbox Code Playgroud)
完全不是我的预期,我也不认为这是Vim所期望的.它看起来像子以某种方式逃避我的报价,但我不知道为什么.
有什么方法可以像我期望的那样让它发挥作用吗?
这只是一个警告,但我想解决它:
Jul 23, 2014 2:31:27 PM org.apache.catalina.startup.SetContextPropertiesRule begin
WARNING: [SetContextPropertiesRule]{Context} Setting property 'debug' to '1' did not find a matching property.
Run Code Online (Sandbox Code Playgroud)
我不确定这实际上是在哪里设置的1,或者是哪个属性。我看到其他一些问题也有同样的警告,但没有一个答案适用 - 我正在使用 Tomcat 7,事实上,它确实在类路径上有tomcat-util和。tomcat-jdbclog4j.jar
我在 Ubuntu 12.04 64 位下运行 Tomcat 7。
为Spring 创建自定义ObjectMapper很容易,但配置需要XML.我正在尝试减少真正不会改变的事情的XML配置量,而无需重新部署我的整个系统.
所以标题说明了一切 - 我可以使用注释或其他非XML方法来告诉Spring,"嘿,请使用我的自定义对象映射器"?
编辑:
这似乎不起作用
@Configuration
@EnableWebMvc
public class AppConfig {
@Primary
@Bean
public ObjectMapper mapper(){
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
mapper.registerModule(new JodaModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑2: 我不相信Spring正在使用我的 ObjectMapper.我有这个代码:
@Primary
@Bean
public ObjectMapper mapper(){
ObjectMapper mapper = new ObjectMapper();
JodaModule mod = new JodaModule();
mod.addSerializer(DateTime.class, new JsonSerializer<DateTime>() {
@Override
public void serialize(DateTime dateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
System.out.println("Hi, bob");
}
});
mapper.registerModule(mod);
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
return mapper; …Run Code Online (Sandbox Code Playgroud) 我在Windows上有一个简单的测试应用程序 - 运行Flask wsgi应用程序的Tornado.我可以很好地启动服务器并通过我的网络浏览器连接,这很酷.
我可以运行我的性能测试,在我的机器上我每秒可以获得约900-1000个请求.但是,在大约20,000个请求之后,我的服务器停止响应并且我的测试报告每秒0.我可以尝试通过Web浏览器进行连接,但没有.通常情况下,ctrl+ c也存在一些问题(在浏览器中刷新页面之前必须多次点击才能正常结束服务器).
那么为什么我的服务器在这样敲击它时会窒息而死?
好吧,所以在试图排除不同因素的过程中 - 我能够从不同的机器上击中服务器,即使我的本地机器正在bar,所以看起来它实际上是我的本地机器用完了端口或什么的?
无论如何,这是我的代码:
server.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def main():
return "Hey, it's working"
if __name__ == "__main__":
app.run("0.0.0.0", port=5000, debug=True)
Run Code Online (Sandbox Code Playgroud)
tornado_server.py
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from server import app
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(5000)
IOLoop.instance().start()
Run Code Online (Sandbox Code Playgroud)
perftest.py
from socket import *
import time
n = 0
stop = False
from threading import Thread
def monitor():
global n, stop …Run Code Online (Sandbox Code Playgroud) 我有一些看起来像这样的代码:
from functools import lru_cache
@lru_cache()
def get_cheese(type):
print('{}? We\'re all out.'.format(type))
return None
get_cheese(type='cheddar')
get_cheese('cheddar')
print(get_cheese.cache_info())
Run Code Online (Sandbox Code Playgroud)
cache_info()报告有两个遗漏-但是我使用相同的参数调用了该函数。
它实际上需要做一些事情,但我发现这是因为在一种情况下,我使用了关键字arg,而另一种情况下,我使用了位置参数。
但是为什么呢?
我试图在python中解释一个异步编程的例子,但我失败了.这是我的代码.
import asyncio
import time
async def asyncfoo(t):
time.sleep(t)
print("asyncFoo")
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncfoo(10)) # I think Here is the problem
print("Foo")
loop.close()
Run Code Online (Sandbox Code Playgroud)
我的期望是我会看到:
Foo
asyncFoo
Run Code Online (Sandbox Code Playgroud)
等待10秒才asyncFoo显示出来.
但相反,我没有得到任何10秒,然后他们都显示.
我做错了什么,怎么解释呢?
考虑以下文件:
圣手手榴弹.py
def count(one, two, five='three'):
print('boom')
Run Code Online (Sandbox Code Playgroud)
test_holy_hand_grenade.py
from unittest import mock
import holy_hand_grenade
def test_hand_grenade():
mock_count = mock.patch("holy_hand_grenade.count", autospec=True)
with mock_count as fake_count:
fake_count(1, 2, five=5)
# According to https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_args
# this should work
assert fake_count.call_args.kwargs['five'] == 5
Run Code Online (Sandbox Code Playgroud)
根据文档,call_args应该是:
这要么是 None (如果尚未调用模拟),要么是最后一次调用模拟的参数。这将采用元组的形式:第一个成员,也可以通过 args 属性访问,是调用模拟的任何有序参数(或空元组),第二个成员,也可以通过访问kwargs 属性是任何关键字参数(或空字典)。
(强调我的)
但这在我的脸上炸开了锅 TypeError: tuple indices must be integers or slices, not str
嗯。不?
我真的不明白的是,如果这是一个调用对象,它就是,因为
assert isinstance(fake_count.call_args, (mock._Call,))
Run Code Online (Sandbox Code Playgroud)
通过,它应该有 kwargs 和 args。它……嗯,确实如此。但它们似乎实际上并不是正确的:
assert isinstance(fake_count.call_args.kwargs, (mock._Call,)) #this works
assert isinstance(fake_count.call_args.kwargs, (dict,)) # doesn't …Run Code Online (Sandbox Code Playgroud) python ×8
flask ×2
python-3.x ×2
asynchronous ×1
caching ×1
functools ×1
jackson ×1
java ×1
json ×1
mocking ×1
python-mock ×1
sockets ×1
spring ×1
subprocess ×1
tdd ×1
tomcat ×1
tomcat7 ×1
tornado ×1
unit-testing ×1
vim ×1
wtforms ×1