简体   繁体   中英

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:

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. 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

> python app.py .

Essentially, the application requests JSON data from my Stash repository via their API. Stash's API requires user authentication for this get request. The requests module made it easy to do... I'm avoiding raw HTML as much as possible (web noob... >.<;).

I am getting the following error exception in Python when deployment is on IIS and not sure why:

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. 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.

The permission error was indeed an issue on the IIS side. You have to change IIS's permission settings. This link helped me out:

IIS7 Permission Denied - ASP File Write

In IIS Manager I clicked Application Pools in the Connections pane. Then instead selected my Flask application (not DefaultAppPool as stated in the link). I right-clicked it and selected Advanced settings . Then I changed the Identity field under Process Model section to LocalSystem . Hit OK.

After this change, the python requests module gets a <200> response with successful authentication credentials & avoids the connection error! ^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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