execution python application from browser - python

I have written a python console based program. It takes few arguments (like file name ) for execution.
I want to run it from the browser...
How can I parse this arguments and execute that python code
Any clues..approaches.
Thanks

Maybe you should clarify your problem. At least i don't fully understand why you want to run a terminal program in the browser?
But if you want to reuse some code you have already written you could use a micro framework like Flask.
Check this example from flask's docs:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
So you could write a simple view that accepts the arguments you need and the view would then call your code and return whatever you want, most likely an http response.

Related

Flask keeps executing the same old code even after replacing the code with new one

I am extremely new to flask framework. I wrote a few basic beginner codes in flask and after I did the changes to it, the output doesn't change as is the same code is running behind the scene which I can't figure out.
I Tried:-
Changing the directory of my python file.
Deleting the file and made a new one.
Deleting the browser cache and cookies.
This seems to be a common issue but there's no perfect answer for this question on this site, please help.
Sample code:
from flask import Flask , redirect , url_for, render_template
app = Flask(__name__)
#app.route("/")
def home():
return "Hello bc"
if __name__ == "__main__":
app.run()
I opened the task manager to check if there was any process related to the flask running in the background and ended up closing all the python processes that were running in the background and it's working fine now thanks for the replies.
first of all enable the debug true that helps
app.run(debug=True)
This will display flask restarting in the terminal when you update the code.
Second, try hard refresh of the browser by pressing CTRL+SHIFT+R
For sake of better coding and work with flask in future id suggest you setting up venv variablies like FLASK_APP=app.py , FLASK_DEBUG=1. And using flask run in your terminal.
Im not sure wich OS you are using on windows u can use set FLASK_DEBUG=1 , on linux just replace set with export FLASK_DEBUG=1.

I'm Getting 404 Not Found for Flask Code and I can't figure out why

I am attempting to teach myself flask from Medium and YouTube tutorials, and keep running into the same error.
Screenshot of 404 Not Found
Normally, I would assume I messed up, made a spelling mistake, and shouldn't embarrass myself by asking how to fix it on a public forum, but I literally copy-pasted the code without making any changes.
I found a Medium post that walks you through step-by-step with simple instructions and ran the code
from flask import Flask # import flask
app = Flask(__name__) # create an app instance
#app.route("/") # at the end point /
def hello(): # call method hello
return "Hello World!" # which returns "hello world"
if __name__ == "__main__": # on running python app.py
app.run() # run the flask app
and continue to get the same error. Does anyone know what I'm doing wrong?
Screenshot of Pycharm
Can you try changing app.run() to app.run(debug=True) and then restart the server?
Also, after restarting try visiting the link in incognito just to make sure it's not a caching issue.
As Medium explains further on in that tutorial:
For development purposes, we use something called as debug mode. When debug=True is set the server restarts as we add new code to our Flask Application.
So, I tried all of these and nothing worked. Then I restarted the computer and it still didn't work. And then I restarted is 2 more times and it worked, so I don't know what happened.

Python: Read POST Parameters

I've never used python before but need to write a fairly simple script for a project I'm working on. All I need is a script that listens on port 80 for incoming HTTP POSTs and prints the posted variables/parameters and values to the command line.
What's the easiest way for a beginner to get this done?
Thanks.
Consider using Flask Framework. With just 7-8 lines your job is done.
It will print all parameter sent using post and get request to your console.
Also I would recommend to learn it.
from flask import Flask
app = Flask(__name__)
#app.route("/",methods=['POST','GET'])
def index():
print request.form
return "Please Check your command line"
if __name__ == "__main__":
app.run(host='0.0.0.0',port=80,debug=True)

How do you debug url routing in Flask?

I'm developing a Flask website using Visual Studio 2013's PythonTools, which has its own debugger, and that allows me to step through the initial setup code, up until app.run()
However the code I want to debug is the routing code, like this:
#app.route('/')
def url_index():
return render_template('index.html')
I know that function is running because the server does respond with index.html, but if I put a breakpoint on the last line, it'll never get hit.
Is there any way to debug these routing functions? Flask says it comes with a debugger but how do I use it? Will it be compatible with Visual Studio?
For the Flask debugger, you can set app.debug to True:
app.debug = True
or
app.run(debug=True)
And then:
#app.route('/')
def index():
raise
return render_template('index.html')
And then you can debug the function with the Flask debugger in your browser.
6 months later, and while it still doesn't look possible to automatically debug URL routing in flask, you can manually attach a debugger to the flask process, though you'll have to re-add it if you restart the server or if the auto-reloader detects changes in your .py files and restarts.
Just go:
Tools -> Attach to Process
and select the Python.exe that is not greyed out (that's the initial flask code that visual studio is already debugging), and then do something that would cause the breakpoint to be hit (e.g. reload the page), and you should have success.
Sadly the current version of PTVS doesn't support Flask projects.
Good thing is: the already released PTVS 2.1 alpha does: http://pytools.codeplex.com/wikipage?title=Flask
You can turn off reloading with debug mode by using
app.run(debug=True, use_reloader=False)
The Flask error handling docs go into the details of the debugging options.

Output from a Python page call by a JQuery getJSON function

I'm working on a website that uses Python web.py. There is a form where the user enters input and when the submit button is hit, a python page is called (matches) using the .getJSON JQuery function show below.
function buildMatches(input){
$.getJSON("/matches", {e:input}, function(json){
//Returned JSON object is worked on
}
}
The "matches" python page grabs a value from a DB, runs some string reg ex and returns a JSON object. Everything works fine, my question is how would I be able to output something from the python page "matches" to see what is exactly happening during the reg ex operations? I've tried print "" (python 2.5), but I understand that would print to the console. I've done some research but couldn't find anything for my situation. I don't necessarily need to print it out to the HTML page, just any where where I can see what's going on. Thanks in advance for any help.
I have access to the webserver (SSH, SFTP, etc.), I tried to log by importing the logging module, below is the code I used. I could get it to log if I ran the page from the command line, but not when it is called by the JS page.
import logging
logging.basicConfig(filename='./SomeClass.log', filemode='w', level=logging.DEBUG)
class SomeClass:
logging.info('Started')
logging.info('Another log')
def __init__(self, obj):
logging.info('In the init')
def another_functio(self):
logging.info('Logging inside the function')
I've tried setting the full path of the log and I still have the same problem where the log file will only be written or updated when I run this class from the console. This doesn't work when the class is called by the webserver.
logging.basicConfig(filename='/home/.../.../.../example.log', filemode='w', level=logging.DEBUG)
Depending on how much access you have to the web server you can run your code manually so web.py uses its built-in web server. Then print statements will end up on the console.
Otherwise, have you thought about simply writing to your own log file somewhere accessible with a browser?
Thanks again for all the help. After digging more into the setup of the Apache server and Python implementation I was able to find a solution to help me see what's going and debug my web app. I saw that Apache config is setup to log errors and WSGI also blocks (pukes on) std.out. What I was able to do is redirect the print command to the Apache error log files.
print >> sys.stderr, "Debugging print with variable" + variable
Then I check the Apache error log to start debugging the web app. I thought I would share this in case anyone else ran into this problem as it was a pain for me.
Thanks again.

Categories