用telnet运行python脚本

时间:2014-02-15 21:07:10

标签: python telnet

我正在使用localhost来测试python脚本,我需要通过telnet测试它,我正在使用PuTTY。我有这个python脚本:

@app.route('/add/', methods=['POST'])
def add_entry():
    db = get_db()
    db.execute('insert into entries (title, text) values (?, ?)',
                 ("value_from_telnet", "another_value_from_telnet"))
    db.commit()
    print("Saved")
    return "Saved"

现在我不知道如何连接到127.0.0.1/add以及如何将值放入POST方法。我无法使用这样的连接:

$ o 127.0.0.1/add

如果我试试这个:

$ o 127.0.0.1
$ GET / HTTP/1.0
$ Host: 127.0.0.1/add

然后结果是404 NOT FOUND(通过浏览器它可以工作,但只有静态插入值和GET方法)。所以我想问一下如何连接到这个地址127.0.0.1/add并获取POST方法的值,以便将它们用作数据库的插入值?谢谢

1 个答案:

答案 0 :(得分:2)

改为使用curl:curl -v -X POST 'http://<ip.address.of.server>/add' --data "title=foo&text=baz and spam and eggs"

对于telnet中的帖子,您需要指定请求的主体,如下所示:

POST /add HTTP/1.1
Content-type:application/x-http-form-urlencoded

title=foo&text=baz+and+spam+and+eggs

如果要从字典构建查询字符串,则需要urllib

import urllib

params = {title:"foo",text:"baz and spam and eggs"}

print """
POST /add HTTP/1.1
Content-type:application/x-http-form-urlencoded

""",urlencode(params)