Flask函数url_for不适用于Bluehost上的子域部署 [英] Flask function url_for doesn't work for sub-domain deployment on Bluehost

查看:228
本文介绍了Flask函数url_for不适用于Bluehost上的子域部署的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Bluehost的根目录下的一个子目录中部署了一个名为app的非常简单的Flask应用程序。希望example.com指向主页,example.com/app指向我的Flask应用程序。实际上,当脚本index.py如下所示时,Flask应用程序工作得很好:

  from flask import Flask 

app = Flask(__ name__)

@ app.route('/',methods = ['GET'])
def home():
return'Hello世界'

if __name__ ==__main__:
app.run()

但是,由于我引入了一个简单的登录功能,因此doc结构和index.py看起来像这样:

doc结构:

  public_html 
| --app
| - 。htaccess
| --index.fcgi
| --index.py
| --static
| --login.html
| --templates
| --home.html

index.py:

  from flask import Flask,url_for,request,render_template,redirect,session $ b $ app = Flask(__ name__)

app.route('/',methods = ['GET'] )
def home():
如果不是session.get('user'):
返回重定向(url_for('login'))#go登录页面如果没有登录
else:
return render_template('home.html')#otherwise转到主页

@ app.route('/ login',methods = ['GET','POST' ])
def login():$ b $如果request.method =='GET':
返回app.send_static_file('login.html')
else:
user = request.form.get('user')
password = request.form.get('password')
if user =='joy'and password =='joy':
session ['user'] = user
return render_template('home.html')
else:
return'LOGIN FAILED'

if __name__ == __main__:
app.run()

/ app导致example.com/login更改的URL和一个合理的404错误example.com/login不会映射到任何文档。
$ b

  return redirect(url_for('login'))

url_for('login')返回example.com/login而不是example.com/app/login 。这就是为什么index.py的后一个版本不起作用。我尝试了很多东西,但没有遇到任何问题。请帮忙。谢谢!



我的.htaccess:

 选项+ ExecCGI 
AddHandler fcgid-script .fcgi
RewriteEngine On
#RewriteBase / app /#RewriteBase / or RewriteBase / app / work
RewriteCond%{REQUEST_FILENAME}!-f
RewriteRule ^(。*)$ index.fcgi / $ 1 [QSA,L]

我的index.fcgi:

  import sys 
sys.path.insert(0,'/ path_to_my_python_site-packages')

from flup.server.fcgi从索引导入WSGIServer
导入应用程序
$ b $ class ScriptNameStripper(object):
def __init __(self,app):
self .app = app
$ b $ def __call __(self,environ,start_response):
environ ['SCRIPT_NAME'] =''
返回self.app(environ,start_response)

app = ScriptNameStripper(app)
$ b $ if if __name__ =='__main__':
WSGIServer(app).run()


解决方案

以下现在为我工作。


  1. 注释.htaccess中的RewriteBase

  2. .py用自定义的url_for

      from flask import烧瓶,重定向,url_for 
    $ b $ app =烧瓶__name__)
    $ b $ def strip_url(orig):
    return orig.replace('index.fcgi /','')

    @ app.route('/ ',方法= ['GET'])
    def home():
    返回重定向(strip_url(url_for('login')))

    @ app.route(' / login',methods = ['GET'])
    def login():
    返回'please login'

    if __name__ ==__main__:
    app.run()


我想说官方的 Flask fastcgi docs 需要一个RewriteRule来从网址中删除***。fcgi不起作用的重定向从代码内启动。

I deployed a very simple Flask application called 'app' in a sub directory under root directory in Bluehost. Hopefully, example.com points to the homepage and example.com/app points to my Flask application. Actually, the Flask application works pretty fine when the script index.py looks like:

from flask import Flask

app = Flask(__name__)

@app.route('/', methods=['GET'])
def home():
    return 'Hello world'

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

But things went bad as I introduced a simple login functionality, with the doc structure and index.py look like:

doc structure:

public_html                     
|--app                          
     |--.htaccess
     |--index.fcgi
     |--index.py
     |--static
        |--login.html
     |--templates
        |--home.html

index.py:

from flask import Flask, url_for, request, render_template, redirect, session
app = Flask(__name__)

@app.route('/', methods=['GET'])
def home():
    if not session.get('user'):
        return redirect(url_for('login'))     #go to login page if not logined
    else:
        return render_template('home.html')   #otherwise go to home page

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return app.send_static_file('login.html')
    else:
        user = request.form.get('user')
        password = request.form.get('password')
        if user == 'joy' and password == 'joy':
            session['user'] = user
            return render_template('home.html')
        else:
            return 'LOGIN FAILED'

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

However, accessing example.com/app led to a changed URL as example.com/login and a reasonable 404 error as example.com/login doesn't map to any document.

return redirect(url_for('login'))

The url_for('login') return example.com/login instead of example.com/app/login. That's why the latter version of index.py doesn't work. I tried so many things but didn't came across any fix. Please help. THanks!

My .htaccess:

Options +ExecCGI
AddHandler fcgid-script .fcgi
RewriteEngine On
#RewriteBase /app/        # Neither RewriteBase / or RewriteBase /app/  work
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]

My index.fcgi:

import sys
sys.path.insert(0, '/path_to_my_python_site-packages')

from flup.server.fcgi import WSGIServer
from index import app

class ScriptNameStripper(object):
   def __init__(self, app):
       self.app = app

   def __call__(self, environ, start_response):
       environ['SCRIPT_NAME'] = ''
       return self.app(environ, start_response)

app = ScriptNameStripper(app)

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

解决方案

The following works for me now.

  1. Comment RewriteBase in .htaccess

  2. Updated index.py with a customized url_for

    from flask import Flask, redirect, url_for
    
    app = Flask(__name__)
    
    def strip_url(orig):
       return orig.replace('index.fcgi/', '')
    
    @app.route('/', methods=['GET'])
    def home():
        return redirect(strip_url(url_for('login')))
    
    @app.route('/login', methods=['GET'])
    def login():
        return 'please login'
    
    if __name__ == "__main__":
        app.run()
    

If a conclusion has to be made, I would like say official Flask fastcgi docs demands a RewriteRule to remove the ***.fcgi from the url which doesn't work for redirect initiated from within code.

这篇关于Flask函数url_for不适用于Bluehost上的子域部署的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆