Python script with flask - how to enable setup on windows server - python

I have a python script with flask API. I am running the code in command line python scriptname.py and making an POST call and it works.
But in realtime how to enable this set up on windows server, so that script is running and available anytime for third-party to make HTTP post. Any pointers please.
class Impersonate:
def __init__(self,login,password):
self.domain='<domain>'
self.login=login
self.password=password
def logon(self):
self.handel=win32security.LogonUser(self.login,self.domain,self.password,win32con.LOGON32_LOGON_INTERACTIVE,win32con.LOGON32_PROVIDER_DEFAULT)
win32security.ImpersonateLoggedOnUser(self.handel)
def logoff(self):
win32security.RevertToSelf() #terminates impersonation
self.handel.Close() #guarantees cleanup
a=Impersonate('testuser','password]')
try:
a.logon() #become the user
print(a.login)
a.logoff() #return to normal
except:
pass
app = Flask(__name__)
api = Api(app)
class Hellow(Resource):
def post(self):
path = os.path.join(parentdir, dirname)
try:
os.makedirs(path)
resp = Response('{} successfully created.)
api.add_resource(Hellow, '/test')
if __name__ == "__main__":
app.run(port=5000, host="<hostname>" use_reloader=True)

You either need to deploy the flask backend on server or on windows you can use "start /b python xyz.py". Or can also have a look at https://www.howtogeek.com/50786/using-srvstart-to-run-any-application-as-a-windows-service/

Related

How to create an API server with endpoints in Python?

Using Python, I would like to create an API server with the following endpoints:
/metric - needs to return the number of times the API server has been called
/health - needs to return ok
Since you don't specify any framework ou give any initial code, here's a simple example using Flask on how it would be:
from flask import Flask
app = Flask(__name__)
count = 0
#app.route('/metric')
def metric():
global count
count += 1
return str(count)
#app.route('/healthz')
def health():
return "ok"
app.run()
To install Flask, run:
pip3 install flask
Run the python code and access on your browser http://127.0.0.1:5000/metric and http://127.0.0.1:5000/healthz
FastAPI is a great option. FastAPI is a "fast (high-performance), web framework for building APIs". It provides interactive API documentation (provided by Swagger UI) to visualize and interact with the API’s resources.
Working Example
You can access the interactive API autodocs at http://127.0.0.1:8000/docs. You can also access the API endpoints directly from the browser at, for instance, http://127.0.0.1:8000/metric.
import uvicorn
from fastapi import FastAPI
app = FastAPI()
hits = 0
#app.get("/metric")
async def metric():
global hits
hits+=1
return {"hits": hits}
#app.get("/health")
async def health():
return "ok"
if __name__ == '__main__':
uvicorn.run(app, host="0.0.0.0", port=8000)

How to invoke/run a Python script using a web URL?

I have a Python script that pulls data from a 3 rd party API. Currently this Pyhton script is automated on server side.
There are few instances where I have to toggle the script manually for new data updates. For the manual toggle I have to login to the server each time and run it from command line. Is there a way where I can create web url or something similar and just run that URL to make that script run from the browser address bar.
One approach you could take is to use Flask, which is a minimal web framework. Here's an example of how you could use it:
from flask import Flask
from your_script import your_func
app = Flask(__name__)
#app.route('/run')
def run_command():
your_func()
return 'Executed your function!'
if __name__ == '__main__':
app.run(debug=False, port=8080)
If you run this code you'd get a web server running on port 8080 that executes your function when you access the url. Here's a tutorial in the Flask documentation to get you started.
I think the easiest way to do this is by using Flask.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
# your code here
return 'Hello, World!'

Python Flask REST API on Windows Cherrypy

I'm trying to create a python Flask REST web API. Since Flask development server is not suitable for production, I tried to use cherrypy application server.
Following is the Flask app I tried to expose via cherrypy
from flask import Flask,request
from flask_restful import Api,Resource, reqparse
app= Flask(__name__)
api = Api(app)
class Main (Resource):
def get(self):
return "Hello Flask"
if __name__ == '__main__':
api.add_resource(Main, "/testapp/")
app.run(debug=True)
Following is the cherrypy script I have created
try:
from cheroot.wsgi import Server as WSGIServer, PathInfoDispatcher
except ImportError:
from cherrypy.wsgiserver import CherryPyWSGIServer as WSGIServer, WSGIPathInfoDispatcher as PathInfoDispatcher
from stack import app
d = PathInfoDispatcher({'/': app})
server = WSGIServer(('127.0.0.1', 8080), d)
if __name__ == '__main__':
try:
server.start()
print("started")
except KeyboardInterrupt:
server.stop()
I have saved this script as "run.py" in my project directory. When I run this it doesn't show any error, which made me to thin this is correct.
But unfortunately I cant access this using the url
Theoretically, url for this API should be some thing like follow
http://127.0.0.1:8080/testapp/
But it throws 404 with the message
"The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
What am I doing wrong ?
The
api.add_resource(Main, "/testapp/")
in your file stack.py is not executed if the file is included from your run.py
as the condition
if __name__ == '__main__':
...
is not true (in the context of stack.py).
Moving the call to api.add_resource(...) to a position outside the if-main-condition (so it is always executed) should solve the issue.

how to create a flask web service when asp.net as the frontend

I have built a web application using asp.net. and created a web service using command prompt process-System.Diagnostics.process usually ill get the values from the user then pass it to the server's cmd prompt, this will run the python script using the given values as python script parameters.
As it is running by cmd-System.Diagnostics.process, it takes more time to initialize and run the script.
So I decided to go with Flask framework, I tried with some html files and works fine, but while working with asp.net as front end. It is not working as expected.
My pythonscript:
from flask import Flask, redirect, url_for, request, render_template
app = Flask(__name__)
#app.route('/success/<name>')
def success(name):
return "<h1>'welcome %s' </h1>"% name
#app.route('/Login.aspx',methods = ['POST', 'GET'])
def login():
if request.method == 'POST':
user = request.form['nm']
return redirect(url_for('success',name = user))
else:
user = request.args.get('nm')
return redirect(url_for('success',name = user))
#app.route("/index/<name>")
def index(name):
return render_template('hello.html',name=name)
#app.route('/hello/<int:score>')
def hello_name(score):
return render_template('marks.html', marks = score)
if __name__ == '__main__':
app.run(debug = True)
I also tried changing to the visual studio port in app.run(debug = True,port=62500) I am getting OSError: [WinError 10013] An attempt was made to access a socket in a way forbid
den by its access permissions please help.
Or suggest me any other way of creating web service to run my python script in server from a asp.net webpage

Cloud9: Running a python server

In my Cloud9 IDE, which is running on Ubuntu I have encountered a problem in trying to reach my Python server externally. It's because their projects use a non-standard naming structure:
https://preview.c9users.io/{user}/{project}/
Changing the address to something like this, which is the default server address, doesn't help:
https://preview.c9users.io:8080/{user}/{project}/
I'm looking for a solution so I can run the following script or for a way to be able to combine HTML+JS+Python on Cloud9. The purpose of the server should be to respond to AJAX calls.
The Cloud9 server is Ubuntu-based, so there may be other ways to address this problem than just my script below.
import web
def make_text(string):
return string
urls = ('/', 'tutorial')
render = web.template.render('templates/')
app = web.application(urls, globals())
my_form = web.form.Form(
web.form.Textbox('', class_='textfield', id='textfield'),
)
class tutorial:
def GET(self):
form = my_form()
return render.tutorial(form, "Your text goes here.")
def POST(self):
form = my_form()
form.validates()
s = form.value['textfield']
return make_text(s)
if __name__ == '__main__':
app.run()
The server above actually runs and is available through URL in special format. It has been changed since earlier version, so I couldn't find it at first:
http://{workspacename}-{username}.c9users.io
Now I prefer to run it as a service (daemon) in the console window to execute additional scripts in the backend and test frontend functionality.

Categories