[Flask] Executing user input python code inside flask app context
David Nieder
davidnieder at gmx.de
Tue Aug 23 06:41:13 EDT 2016
On 21.08.2016 19:24, Alex Alex wrote:
> Hi,
>
>
>
> I'm working on flask based webapp that requires users to be able to eneter and execute python code (+ presenting exeuction output) within flask app context. As I'm new to flask (and I love it) I'd be greatful for any tips regarding implementing such functionality. As a side note: the security is not a concern so please don't responde with code snippets containg os.system('rm -rf /') as example of dangerus user input. I'm also not interested in running code inside pypy sandbox (at least not on
> this stage).
>
> Thank you in advance
> BR
> Alex
>
>
Hi Alex.
You could use the code module:
https://docs.python.org/2.7/library/code.html
Here is a very minimal but working example of how you could go about it:
import sys
from StringIO import StringIO
from code import InteractiveInterpreter
from flask import Flask, request, Response
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return '''
<form action="/" method="post">
<input type="text" name="user-input">
<input type="submit">
</form>
'''
remember_stdout = sys.stdout
stdout = StringIO()
sys.stdout = stdout
interpreter = InteractiveInterpreter({
'__name__': 'console',
'__doc__': None,
# add objects you want to make available here, e.g.
'app': app,
'request': request
})
interpreter.runsource(request.form.get('user-input'))
sys.stdout = remember_stdout
return Response(stdout.getvalue(), mimetype='text/plain')
if __name__ == '__main__':
app.run(debug=True)
You probably want to extend this quite a bit (support multi-line
statements, input history, ...).
Take a look at the werkzeug debug console which does a similar thing.
And since you have werkzeug installed you could directly use a lot of
it's code.
https://github.com/pallets/werkzeug/tree/master/werkzeug/debug
You stressed security is not a concern but I have to note anyway that
this is highly insecure and people got hacked before having sth like
this exposed on the web.
Hope this was helpful
David
More information about the Flask
mailing list