【问题标题】:Python Local Server For Callback URL回调 URL 的 Python 本地服务器
【发布时间】:2020-09-15 22:39:18
【问题描述】:

我正在开发一个 oauth 项目,该项目需要我有一个回调 url,可以在成功授权后加载以请求访问令牌,但我不确定如何以正确的方式运行该服务器。我熟悉有用的单行 python 服务器设置python -m http.server,但这只会加载我启动服务器的目录,并充当用于导航该目录中文件的服务器。

是否有首选方法来设置可用于此重定向过程的简单服务器并进行我需要的额外服务器调用?我需要使用像 Django 这样的网络框架吗?

【问题讨论】:

  • 你需要可以在服务器上运行代码的服务器(Python/PHP/Ruby/etc.)你可以使用选项--cgipython -m http.server --cgi),然后它可以运行文件夹@987654324中的脚本@ - http://localhost/cgi-bin/script.py。但是CGI 方法是非常古老的方法,可能更有用的是使用更新的东西,比如 web 框架FlaskBottleDjango

标签: python oauth-2.0 localhost


【解决方案1】:

使用python -m http.server,您只能提供静态文件,但您需要运行一些获取参数并使用它的代码。

您可以在python -m http.server --cgi 中使用选项--cgi,然后您可以将脚本(任何语言)放入文件夹cgi-bin 并运行它http://localhost/cgi-bin/script.py

但是CGI 的方法已经很老了,使用microframework 的一些网络会更容易,比如Flaskbottle

script.py

from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def index():
    print('args:', request.args)  # display text in console
    #print('form:', request.form)
    #print('data:', request.data)
    #print('json:', request.json)
    #print('files:', request.files)
    
    return request.args.get('data', 'none')  # send text to web browser

if __name__ == '__main__':
    app.run(port=80, debug=True)

并以python script.py 运行并在网络浏览器中进行测试

http://127.0.0.1/?data=qwerty

request.args.get("data") 应该会给你qwerty,你可以在 Python 代码中使用它。

【讨论】:

  • 感谢您的解释!这非常有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-30
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
  • 2016-02-16
  • 2017-05-31
相关资源
最近更新 更多