简体   繁体   English

Flask对IIS上的Python请求 连接错误

[英]Python's Requests on IIS with Flask | Connection Error

I've been working to get Flask applications up running on my IIS server and have made some progress thanks to the below link: 我一直在努力使Flask应用程序在IIS服务器上运行,并且由于以下链接而取得了一些进展:

http://netdot.co/2015/03/09/flask-on-iis http://netdot.co/2015/03/09/flask-on-iis

With that stated, I am running into a head scratcher when attempting to use the "requests" python module when I deploy over IIS. 这样说来,当我通过IIS进行部署时,尝试使用“请求” python模块时,我遇到了麻烦。 The application works fine when I launch it locally -- that is, I get a proper <200> response when requesting the JSON data if I launch the app via terminal 当我在本地启动该应用程序时,该应用程序运行良好-也就是说,如果我通过终端启动该应用程序,则在请求JSON数据时收到正确的<200>响应

> python app.py . > python app.py

Essentially, the application requests JSON data from my Stash repository via their API. 本质上,该应用程序通过其API从我的Stash存储库请求JSON数据。 Stash's API requires user authentication for this get request. Stash的API需要对此get请求进行用户身份验证。 The requests module made it easy to do... I'm avoiding raw HTML as much as possible (web noob... >.<;). 请求模块使操作变得很容易...我正在尽可能避免使用原始HTML(Web noob ...>。<;)。

I am getting the following error exception in Python when deployment is on IIS and not sure why: 在IIS上部署时,我在Python中收到以下错误异常,但不知道为什么:

ConnectionError: ('Connection aborted.', error(13, 'Permission denied'))

You can reference the entire code below (confidential stuff omitted). 您可以在下面引用整个代码(忽略机密内容)。 Basically, I have a login.html page that takes user credentials. 基本上,我有一个login.html页面,其中包含用户凭据。 Then, I use those credentials to send the get request 然后,我使用这些凭据发送获取请求

try:
    reqLib = requests.get('https://stash/rest/api/latest/projects/PLAN/repos/sqlquerylibrary/files?at=refs%2Fheads%2Fmaster&limit=100000', auth=(usr, pwd), verify=False)
except Exception as e:
    return str(e)

Entire App: 整个应用程序:

import requests
from flask import Flask, render_template, redirect, url_for, request, send_from_directory
from flask_login import LoginManager, UserMixin, login_required, login_user
import sys
import os

app = Flask(__name__)
login_manager = LoginManager()
login_manager.init_app(app)

user = ''
reqLib = ''

#Add headers to force no-cache
@app.after_request
def add_header(r):
    r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    r.headers["Pragma"] = "no-cache"
    r.headers["Expires"] = "0"
    r.headers["Cache-Control"] = "public, max-age=0"
    return r

#post-processing/loading screen -- you can ignore this route
@app.route("/scripting")
@login_required
def script():
    scrape()
    return redirect(url_for('display'))

#Page displays AFTER a successful <200> response
@app.route("/sqlLibraryDisplay",methods=["GET"])
@login_required
def display():
    return send_from_directory("static","index.html")

#Login Page
@app.route('/sqlLibrary', methods=['GET', 'POST'])
def login():
    error = None
    global reqLib
    global user

    if request.method == 'POST':
        #Grabs username & password entered by user
        usr = str(request.form['username'])
        pwd = str(request.form['password'])

        #Requests SQL Library list from Stash repository
        try:
            reqLib = requests.get('https://stash/rest/api/latest/projects/PLAN/repos/sqlquerylibrary/files?at=refs%2Fheads%2Fmaster&limit=100000', auth=(usr, pwd), verify=False)
        except Exception as e:
            return str(e)

        if reqLib.status_code != 200:
            error = 'Invalid Credentials. Please try again.'
        else:
            user = User(usr,pwd)
            login_user(user)
            return redirect(url_for('script'))

    return render_template('login.html', error=error)

@login_manager.user_loader
def load_user(id):
    global user
    global reqLib

    if user != '':
        if reqLib.status_code == 200:
            return user

    return None

class User(UserMixin):

    def __init__(self, name, id, active=True):
        self.name = name
        self.id = id
        self.active = active

    def is_active(self):
        return self.active

    def is_anonymous(self):
        return False

    def is_authenticated(self):
        return True

def scrape():
    #confidential. Just some post-processing using reqLib data.

if __name__ == "__main__":
    app.config["SECRET_KEY"] = "MAD_SECRET_KEY"
    app.run()

I found the answer. 我找到了答案。 Posting to help out anyone who decides to implement Flask on IIS that might run into this same issue. 发布以帮助决定在IIS上实施Flask的任何人,而这可能会遇到同一问题。

The permission error was indeed an issue on the IIS side. 权限错误确实是IIS方面的问题。 You have to change IIS's permission settings. 您必须更改IIS的权限设置。 This link helped me out: 该链接帮助我:

IIS7 Permission Denied - ASP File Write IIS7权限被拒绝-ASP文件写入

In IIS Manager I clicked Application Pools in the Connections pane. 在IIS管理器中,我单击“连接”窗格中的“ 应用程序池 ”。 Then instead selected my Flask application (not DefaultAppPool as stated in the link). 然后改为选择我的Flask应用程序(而不是链接中所述的DefaultAppPool)。 I right-clicked it and selected Advanced settings . 我右键单击它,然后选择“ 高级设置” Then I changed the Identity field under Process Model section to LocalSystem . 然后我将“ 流程模型”部分下的“ 标识”字段更改为LocalSystem Hit OK. 点击确定。

After this change, the python requests module gets a <200> response with successful authentication credentials & avoids the connection error! 进行此更改后,python请求模块将获得带有成功身份验证凭据的<200>响应,并避免了连接错误! ^^ ^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM