使用 Flask、Pyramid 或 Bottle 中的任何一个创建动态重定向?

发布于 2024-12-16 12:26:08 字数 236 浏览 1 评论 0原文

我想创建一个根据用户输入的地址动态重定向到 URL 的 Web 应用程序。当用户通过如下地址访问我的网站时:

http://mydomain1.com/a1b2c3d4

我想将此用户重定向到 URL:

http://mydomain2.com/register.php?id=a1b2c3d4&from=mydomain1.com

I want to create a webapp that dynamically redirects to a URL, based on address that user typed. When a user visit my site by a address like this:

http://mydomain1.com/a1b2c3d4

I want redirect this user to URL:

http://mydomain2.com/register.php?id=a1b2c3d4&from=mydomain1.com

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

﹂绝世的画 2024-12-23 12:26:08

是的,我喜欢一场精彩的战斗!

from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPFound
from paste.httpserver import serve

config = Configurator()

config.add_route('redirect', '/{arg}')

def redirect_view(request):
    dst = 'http://mydomain2.com/register.php?id={id}&from={host}'
    args = {
        'id': request.matchdict['arg'],
        'host': request.host,
    }
    return HTTPFound(dst.format(**args))
config.add_view(redirect_view, route_name='redirect')

serve(config.make_wsgi_app(), host='0.0.0.0', port=80)

Yay, I love a good fight!

from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPFound
from paste.httpserver import serve

config = Configurator()

config.add_route('redirect', '/{arg}')

def redirect_view(request):
    dst = 'http://mydomain2.com/register.php?id={id}&from={host}'
    args = {
        'id': request.matchdict['arg'],
        'host': request.host,
    }
    return HTTPFound(dst.format(**args))
config.add_view(redirect_view, route_name='redirect')

serve(config.make_wsgi_app(), host='0.0.0.0', port=80)
七堇年 2024-12-23 12:26:08

这是我的尝试,我几乎是烧瓶新手,所以它应该有改进的空间

from flask import Flask, redirect, request
app = Flask(__name__)
host = 'domain2.org'

@app.route('/<path>')
def redirection(path):
    return redirect('http://'+host+'/register.php?id='+path+'&from='+request.host)

if __name__ == '__main__':
    app.run()

编辑将主机添加到 from 参数

Here goes my attempt, I'm almost newbie in flask, so it should have room to improve

from flask import Flask, redirect, request
app = Flask(__name__)
host = 'domain2.org'

@app.route('/<path>')
def redirection(path):
    return redirect('http://'+host+'/register.php?id='+path+'&from='+request.host)

if __name__ == '__main__':
    app.run()

Edited to add the host to the from parameter

终止放荡 2024-12-23 12:26:08

我的解决方案是使用路径类型的 Werkzeug 规则:

host = 'domain2.org'
@app.route('/<path:path>')
def redirection(path):
    return redirect('http://%s/%s' % (host, path), code=301)

如果您移动一个站点并想要另一个站点而不是在其他页面上重定向,这会很有用。

My solution was to use a Werkzeug rule using the path type :

host = 'domain2.org'
@app.route('/<path:path>')
def redirection(path):
    return redirect('http://%s/%s' % (host, path), code=301)

This can be useful if you move a site and want another site instead with redirection on others pages.

魔法少女 2024-12-23 12:26:08

有一个pyramid_rewrite扩展(https://pypi.python.org/pypi/pyramid_rewrite/)看起来没有维护,但似乎有效。不过,我有一个它无法处理的用例:使用带有route_prefix参数的Configure.include()。

我想到通常的方法是在服务器中进行 URL 重写,而我使用的是 Python 标准库中的 WSGI 服务器。这有多难?

创建自定义请求处理程序类:

from wsgiref.simple_server import make_server, WSGIRequestHandler

class MyReqHandler(WSGIRequestHandler):
    def get_environ(self):
        env = WSGIRequestHandler.get_environ(self)

        if env['PATH_INFO'].startswith('/foo'):
           env['PATH_INFO'] = env['PATH_INFO'].replace('foo', 'bar', 1)

        return env

在创建服务器时将其传递给 make_server():

srvr = make_server('0.0.0.0', 6543, app, handler_class=MyReqHandler)

它有效!

对于当前的问题,我只需要直接替换即可。将其扩展为使用正则表达式并通过良好的 API 公开它将非常简单。

我有另一个解决方案,那就是直式金字塔,因此它可以与其他一些 wsgi 服务器一起使用:

from pyramid.events import NewRequest, subscriber

@subscriber(NewRequest)
def mysubscriber(event):
    req = event.request

    if req.path_info.startswith('/~cfuller'):
        req.path_info = req.path_info.replace('foo', 'bar', 1)

这是声明性方式,它需要 config.scan()。绝对,你会做类似的事情

config.add_subscriber(mysubscriber, NewRequest)

参见 http:// docs.pylonsproject.org/projects/pyramid/en/1.5-branch/narr/events.html 有关事件的精简信息。

There's a pyramid_rewrite extension (https://pypi.python.org/pypi/pyramid_rewrite/) that looks unmaintained, but seems to work. I had a use case it didn't handle, though: using Configure.include() with the route_prefix parameter.

It occurred to me that the usual approach is to do URL rewrites in the server, and I was using a WSGI server from the Python standard library. How hard could it be?

Make a custom request handler class:

from wsgiref.simple_server import make_server, WSGIRequestHandler

class MyReqHandler(WSGIRequestHandler):
    def get_environ(self):
        env = WSGIRequestHandler.get_environ(self)

        if env['PATH_INFO'].startswith('/foo'):
           env['PATH_INFO'] = env['PATH_INFO'].replace('foo', 'bar', 1)

        return env

Pass it to make_server() when creating your server:

srvr = make_server('0.0.0.0', 6543, app, handler_class=MyReqHandler)

It works!

Straight-up substitution is all I needed for the problem at hand. Extending it to use regular expressions and exposing it via a nice API would be pretty straightforward.

I have another solution, that is straight-up pyramid, so it will work with some other wsgi server:

from pyramid.events import NewRequest, subscriber

@subscriber(NewRequest)
def mysubscriber(event):
    req = event.request

    if req.path_info.startswith('/~cfuller'):
        req.path_info = req.path_info.replace('foo', 'bar', 1)

That's the declarative way, and it requires a config.scan(). Imperitively, you'd do something like

config.add_subscriber(mysubscriber, NewRequest)

See http://docs.pylonsproject.org/projects/pyramid/en/1.5-branch/narr/events.html for the skinny on events.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文