Can't connect to ms sql server using pymssql flask - python

I have an ubuntu server running Apache and am trying to connect to an sql server on the same network.
When I run python in terminal and import pymssqlandthen connect, there are no problems connecting but when I put the same code in the init.py it stops running at the conn=pymssql.connect line. Any body have a clue on this?
__init__.py
from flask import Flask, url_for, render_template
import pymssql
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello, I love Digital Ocean!"
#app.route("/Reports")
def test():
conn=pymssql.connect(server='<fillinServer>', user='<fillinuser>', password='<fillinpassword>', database='<fillindatabase>')
print "1"
cursor=conn.cursor()
cursor.execute("SELECT TOP 1 * FROM testquery;")
print "2"
row=cursor.fetchone()
print "3"
t= row[1]
return render_template("test.html", test=t)
if __name__ == "__main__":
app.run(debug=True)
.WSGI
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/Reports/")
from ReportApp import app as application
application.secret_key = 'Add your secret key'

Try running your code directly from flask.
Change:
if __name__ == "__main__":
app.run(
host="0.0.0.0", #replace this with your ip
port=int("80"), #replace with your port
debug=True)
Make sure all packages and modules are correctly installed in root/virtual environment.
sudo python app.py
If you have tabs and 4 white spaces mixed it will alert you. Clean/debug your script and re-run it.
After fixing these if the script is running in web-browser, it is probably executing your command. My script took a while since I was connecting to a busy BI server.
p.s. add:
print("done")
so you know script has executed properly.
I can tell you that it worked for me.

Related

How do I run a Flask Script from Spyder IDE?

In Spyder, I wrote this code.
Why is it not showing on my browser localhost:5000?
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return "Hello World!"
if __name__ == "__main__":
app.run(debug=True)
Instead of app.run() use app.run(debug = False), for the purpose of running.
How are you running your script? Your code SHOULD work. You have a couple of options:
Navigate to the folder your script is in within a terminal/cmd and enter the following:
python3 script.py
replacing script.py with the actual name of your script
Alternatively:
python3 script.py
If it successfully boots up the flask server it will give you the address and port its running on. By default it should be port 5000 like you have said.
But the address could be:
http://127.0.0.1:5000
localhost:5000
So try both, essentially the same but your computer might be weird.
I'm not familiar with the Spyder IDE, if it has a run button to start the script then press that and you should be able to access the server via either of the above addresses.
You could also try specifying a new port, maybe 5000 is being used?
app.run(port=8080)
Try specifying the host and port like this:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return "Hello World!"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=True)

How to access localhost (flask app) from within docker?

On my laptop I can start simple flask app:
import os
import io
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
s = """
This is a localhost!
"""
return (s)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=3000, debug=True)
And when do curl localhost:3000 on my laptop - I can get a good response.
But when I start a docker image and put same code and start it with same version of Python - it shows as running but when I do from within a docker curl localhost:3000 - do not get any response (it just hangs and nothing happens).
How to enable localhost (routing) inside docker?
Thanks.
Change your code to
app.run(host='127.0.0.1', port=3000, debug=True)
and check if localhost is defined in /etc/hosts.

How to host publicly visible flask server on windows

I am trying to host a flask server from my windows computer so I can access it from external devices
I am using Flask/Python and have already tried a few things but can't get it to work
Tried running it on 0.0.0.0, port 33, 5000, etc. but I still can't access it this way
from flask import Flask, request, abort
app = Flask(__name__)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=33)
When I then run the file I get:
Running on http://0.0.0.0:33/ (Press CTRL+C to quit)
But it isn't even running there, nor on any other way I can access it
I expect to be able to access my flask application and send requests to it by using my public IP address
What can I do here to make it work?
You have missed an important line in your code:
After the line
app = Flask(__name__)
You have to write the line:
#app.route('/')
We use the route() decorator to tell Flask what URL should trigger our function.
And then define a function that will tell what task to be performed in the web app hosted in the respective address.
The function might look something like this:
def hello_world():
return 'Hello, World!'
The complete code then will look like:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=33)
Hope this helps.

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.

flask 'hello world' not working

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.

Categories