I'm using flask_simpleldap and am struggling to get a bind connection to do anything useful.
My LDAP server is active directory.
The stripped down code looks as follows, and looks almost identical to the example:
from flask import Flask
from flask_simpleldap import LDAP
app = Flask(__name__)
app.secret_key = 'super secret key'
app.debug = True
app.config['LDAP_HOST'] = 'my-ldap-host.example.com'
app.config['LDAP_REALM_NAME'] = 'LDAP Authentication'
app.config['LDAP_SCHEMA'] = 'ldaps'
app.config['LDAP_PORT'] = 636
app.config['LDAP_BASE_DN'] = 'dc=example,dc=com'
app.config['LDAP_USERNAME'] = 'binduser#example.com'
app.config['LDAP_PASSWORD'] = 'binduser_pw'
app.config['LDAP_OBJECTS_DN'] = 'distinguishedName'
app.config['LDAP_OPENLDAP'] = False
ldap = LDAP(app)
#app.route('/ldap')
#ldap.basic_auth_required
def ldap_protected():
return 'Welcome, {0}!'.format(g.ldap_username)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
When running the flask app, i'll get an error such as this:
LDAPException: Operations error
While trying to troubleshoot, i've modified flask_simpleldap __init__.py file to show the info as well as the desc of the error, on line 274; Now i get a bit more info about the error:
LDAPException: 000004DC: LdapErr: DSID-0C090752,
comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v2580
So, i guess what i need to understand is why my initial bind won't work... do i have something wrong in my app.config?
Not sure what the problem could be... ldapsearch seems to work from a shell as such:
ldapsearch -x -LLL -E pr=200/noprompt -h my-ldap-host.example.com -D "binduser#example.com" -w 'binduser_pw' -b "dc=example, dc=com" -s sub "(sAMAccountName=binduser)" | grep distinguishedName
distinguishedName: CN=Bind User,OU=Some_OU,DC=example,DC=com
Other details:
I've tried on python2.7 and 3.5, same issues
Centos 7.2
Active Directory is my LDAP server
Any help appreciated, thanks.
Not sure if this is going to be helpful, but I've just set flask_simpleldap to work with our test Active directory instance. The only relevant difference is that I had to use:
app.config['LDAP_USE_SSL'] = True
I think I've also seen "Operations Error" when I had invalid DN or username format.
Your username must be fully qualified.
app.config['LDAP_USERNAME'] = 'uid=binduser,dc=example,dc=com'
Related
I am building a simple flask app, jsonify() works fine on my localhost, it will return the information with new lines and the proper indent in a json format, however when running the exact same code on heroku, it omits the new lines and the indentation
This is how it looks on my localhost and this is on heroku
This is mentioned on the docs for jsonify()
This function's response will be pretty printed if the JSONIFY_PRETTYPRINT_REGULAR config parameter is set to True or the Flask app is running in debug mode
I have both set
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
app.run(debug=True)
I tried manually setting the content type to application/json, but that did not help, I even tried using json.dumps() and got the same result
return jsonify(data), 200, {'Content-Type': 'application/json; charset=utf-8'}
Any input on what could be causing heroku not pretty printing?
Edit:
from flask import request, jsonify, Flask
app = Flask(__name__)
#app.route('/test', methods = ['GET'])
def test():
test_dict = {"Key1": "Value1", "Key2": ["Value2","Value2","Value2",]}
print(jsonify(test_dict).headers)
return jsonify(test_dict)
if __name__ == '__main__':
app.run(debug=True)
This simple flask app would pretty print on my localhost like the photos linked above, however on heroku it wont. Looks like it is returning plain text. It can be seen here https://jojoapi.herokuapp.com/test.
I am using gunicorn, not sure if that has any impacts on the output
Edit 2
So, I set manually debug to True as suggested in the comments app.config["DEBUG"] = True and it works properly on heroku now
Some servers (not only Heroku) may not run directly your script and not execute app(debug=True) but they may import app to own code and run it with own arguments app(...own args...) - and this can makes problem.
You can set debug mode in code in different method.
app.config["DEBUG"] = True
Eventually you can try to set environment variable in Linux
export FLASK_DEBUG=1
or
export FLASK_ENV=development
See doc: Debug Mode
Flask doc: Standalone WSGI Containers - it shows servers which import app (as myproject:app) and they may runs with own arguments.
I have a python application with gunicorn and flask on a centos machine. I access the application from another machine in the following way:
http://host:port/nameOfFunction?path=https://site/directory1/directory2/directory3/file.pdf
The path is correct, because it works. When i enter the same path multiple times, sometimes it works, others, don't.
I am using gunicorn (with the follow command):
gunicorn -b 0.0.0.0:8080 start:app
to start my application. When the answer returns, the screen showing gunicorn prints some piece of code that i put to see some informations.
When it returns me error 500, the code from start isn't printed at all.
I dont have a clue what is the cause of this.
the beginning of the code is:
#app.route("/call", methods=['POST', 'GET'])
def call():
print '\n============================BEGINS======================\n'
path =request.args.get('path')
newPath = path.rsplit('/',1)[1]
directoriesRoot(root)
directoriesRoot(pdfs)
parameters = ["curl", path.replace(' ','%20'), '--output',pdfs+newPath]
p = subprocess.Popen(parameters, stdout=subprocess.PIPE)
output, err = p.communicate()
if err:
return 'ERROR'
person= functionSecundaryWithNoImportance([newPath])
return jsonify(person)
Someone has some clue or already pass for a similar problem?
With the help of user3788685, i found out that my python application was on port 8080 (and probably one of apache's default ports were 8080) so it conflicts. Sometimes it directs to python, others to apache. So i changed the port for my python application to 1234:
gunicorn -b 0.0.0.0:1234 start:app
and now works as a charm!
I copy pasted the flask's 'hello world' app from their website and am trying to run it. I get an error message in Chrome saying
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
Here is the 'hello world' app straight from flasks website
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.debug = True
app.run()
What I have tried:
-temporarily disabling Avast!
-disabling windows firewall
-ensuring that the flask module is installed
This was working a couple days ago actually...
I don't know why but when I change
app.run()
to
app.run(port=4996)
it starts working. No idea why the default port is throwing an error. Oh well.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'Hello World'
if __name__ == '__name__':
app.run()
app.run(port=5000)
For Windows machines you can use the command in cmd:
set FLASK_APP=python_file.py
flask run
Some other process is running on port 5000. It may be you still have an old Flask process running, with broken code. Or a different web server altogether is running on that port. Shut down that process, or run on a different port.
You can switch to using a different port with the port argument to app.run():
app.run(port=8080)
If you can't figure out what process is still bound to port 5000, use the Windows Resource Monitor or run netstat -a -b from a command line. See How can you find out which process is listening on a port on Windows?
I think you are trying to copy the route generated through your flask program in cmd by pressing ctrl+c which quits your running flask program . i was also doing the same.just try to type the route generated by your flask program on your browser . it will definitely resolve your problem.
Where your python file store is, use cmd and then go on your file store directory, then
set FLASK_APP=filename.py
After this your flask run cmd will work.
from flask import Flask
app = Flask(__name__) # creating app
#app.route('/', methods['GET']) #routing it to the home page
def home(): #function
return "hello world"
app.run(port=5000, debug=true) #function call by the app
Add port and use methods whatever your need is USE GET in your case and try to remove your cache and run the this code it will definitely work.
I'm trying to figure out how to run a web service on heroku using flask and JSONRPC.
I would like to get to a point where, from my desktop I can do:
from flask_jsonrpc.proxy import ServiceProxy
service = ServiceProxy('http://<myapp>.heroku.com/api')
result = service.App.index()
print result
looking at heroku logs I can see :
2014-07-05T13:18:42.910030+00:00 app[web.1]: 2014-07-05 13:18:42 [2] [INFO] Listening at: http://0.0.0.0:21040 (2)
and trying using that port with :
service = ServiceProxy('http://<myapp>.heroku.com:21020/api')
still doesn't make it work (it seems hanging)
But when I run this through foreman, though, I can happy access it and seems working fine.
but when I try with the deployed application I get:
ValueError: No JSON object could be decoded
This is the application (not much I know , but is just to see how heroku works)
import os
from flask import Flask
from flask_jsonrpc import JSONRPC
app = Flask(__name__)
jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True)
#jsonrpc.method('App.index')
def index():
return u'Welcome to Flask JSON-RPC'
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', debug=True, port=port)
this is the content of my Procfile:
web: gunicorn run:app -p $PORT
Am I missing something obvious here ?
Cheers.
L.
p.S
accessing http://.heroku.com/api/browse
from within the through foreman and the deployed app, it seems working fine.
[edit]
solved :
yes I was missing something.... looking better a the log I noticed the host which was :
host=<myapp>.herokuapp.com
instead of
.heroku.com
Changing the address to the correct one, it all seems working fine.
http://.herokuapp.com/api
All sorted , see original post.
Sorry for the noise.
I've been working on a new dev platform using nginx/gunicorn and Flask for my application.
Ops-wise, everything works fine - the issue I'm having is with debugging the Flask layer. When there's an error in my code, I just get a straight 500 error returned to the browser and nothing shows up on the console or in my logs.
I've tried many different configs/options.. I guess I must be missing something obvious.
My gunicorn.conf:
import os
bind = '127.0.0.1:8002'
workers = 3
backlog = 2048
worker_class = "sync"
debug = True
proc_name = 'gunicorn.proc'
pidfile = '/tmp/gunicorn.pid'
logfile = '/var/log/gunicorn/debug.log'
loglevel = 'debug'
An example of some Flask code that borks- testserver.py:
from flask import Flask
from flask import render_template_string
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)
#app.route('/')
def index():
n = 1/0
return "DIV/0 worked!"
And finally, the command to run the flask app in gunicorn:
gunicorn -c gunicorn.conf.py testserver:app
Thanks y'all
The accepted solution doesn't work for me.
Gunicorn is a pre-forking environment and apparently the Flask debugger doesn't work in a forking environment.
Attention
Even though the interactive debugger does not work in
forking environments (which makes it nearly impossible to use on
production servers) [...]
Even if you set app.debug = True, you will still only get an empty page with the message Internal Server Error if you run with gunicorn testserver:app. The best you can do with gunicorn is to run it with gunicorn --debug testserver:app. That gives you the trace in addition to the Internal Server Error message. However, this is just the same text trace that you see in the terminal and not the Flask debugger.
Adding the if __name__ ... section to the testserver.py and running python testserver.py to start the server in development gets you the Flask debugger. In other words, don't use gunicorn in development if you want the Flask debugger.
app = Flask(__name__)
app.config['DEBUG'] = True
if __name__ == '__main__':
app.run()
## Tip for Heroku users:
Personally I still like to use `foreman start`, instead of `python testserver.py` since [it sets up all the env variables for me](https://devcenter.heroku.com/articles/config-vars#using-foreman). To get this to work:
Contents of Procfile
web: bin/web
Contents of bin/web, file is relative to project root
#!/bin/sh
if [ "$FLASK_ENV" == "development" ]; then
python app.py
else
gunicorn app:app -w 3
fi
In development, create a .env file relative to project root with the following contents (docs here)
FLASK_ENV=development
DEBUG=True
Also, don't forget to change the app.config['DEBUG']... line in testserver.py to something that won't run Flask in debug mode in production.
app.config['DEBUG'] = os.environ.get('DEBUG', False)
The Flask config is entirely separate from gunicorn's. Following the Flask documentation on config files, a good solution would be change my source to this:
app = Flask(__name__)
app.config.from_pyfile('config.py')
And in config.py:
DEBUG = True
For Heroku users, there is a simpler solution than creating a bin/web script like suggested by Nick.
Instead of foreman start, just use foreman run python app.py if you want to debug your application in development.
I had similiar problem when running flask under gunicorn I didn't see stacktraces in browser (had to look at logs every time). Setting DEBUG, FLASK_DEBUG, or anything mentioned on this page didn't work. Finally I did this:
app = Flask(__name__)
app.config.from_object(settings_map[environment])
if environment == 'development':
from werkzeug.debug import DebuggedApplication
app_runtime = DebuggedApplication(app, evalex=False)
else:
app_runtime = app
Note evalex is disabled because interactive debbugging won't work with forking (gunicorn).
I used this:
gunicorn "swagger_server.__main__:app" -w 4 -b 0.0.0.0:8080
You cannot really run it with gunicorn and for example use the flask reload option upon code changes.
I've used following snippets in my api launchpoint:
app = Flask(__name__)
try:
if os.environ["yourapp_environment"] == "local":
run_as_local = True
# some other local configs e.g. paths
app.logger.info('Running server in local development mode!')
except KeyError as err:
if "yourapp_environment" in err.args:
run_as_local = False
# some other production configs e.g. paths
app.logger.info('No "yourapp_environment env" given so app running server in production mode!')
else:
raise
...
...
...
if __name__ == '__main__':
if run_as_local:
app.run(host='127.0.0.1', port='8058', debug=True)
else:
app.run(host='0.0.0.0')
For above solution you need to give export yourapp_environment = "local" in the console.
now I can run my local as python api.py and prod gunicorn --bind 0.0.0.0:8058 api:app
The else statement app.run() is not actually needed, but I keep it for reminding me about host, port etc.
Try setting the debug flag on the run command like so
gunicorn -c gunicorn.conf.py --debug testserver:app
and keep the DEBUG = True in your Flask application. There must be a reason why your debug option is not being applied from the config file but for now the above note should get you going.