Unable to execute Postgres queries when running with uWSGI - python

I have a basic flask application in which I am connecting with a local Postgres server.
The problem is that the application works fine when I run it using python manager. But when I use uWSGI to run application, the query doesn't executes i.e., it timeouts without throwing any error message.
I have a relatively simple wsgi configuration file like
[uwsgi]
module = wsgi
master = true
processes = 1
http = 0.0.0.0:5000
buffer-size = 32768
vacuum = true
die-on-term = true
My flask application uses psycopg2 to connect with localhost like
connection = psycopg2.connect(
host='127.0.0.1',
port=5432,
database='db',
user='user',
password='password'
)
I think this might probably be happening because postgresql socket is not accessible by uWSGI (reference). I believe this can be solved by providing postgres socket permission to uWSGI, but I am unable to figure out how. If there is another solution than that will also work.

Related

Trying to make a simple python web server and its not starting

Ive been trying to make a web server and I have the code down that should be able to get it running but when I go in to the Command Prompt and type python app.py it doesn't run when it should this is the code that I have
from flask import Flask
app = Flask(__name__)
#app.route("/")
def main():
return "Welcome to my Flask page"
if __name__ == "__main__":
app.run(debug = True, host = "0.0.0.0", port=80)```
The server won't run on port 80, it will run on the default port (5000). If you run the server and navigate to HTTP://0.0.0.0:5000/, you should see your / response. See Why can't I change the host and port that my Flask app runs on?.
To change the port Flask runs on, you can specify it in the command line:
flask run -h localhost -p 3000
Here, I run the server on localhost:3000. If you try to run the server on port 80, you will get a permission denied error since any port under 1024 needs root privileges (as m1ghtfr3e said in their answer).
Also, this is a great tutorial I recommend to anyone learning flask https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
I think the problem is port 80.
Which OS are you using?
Ports under 1024 need root privileges, there is also a possibility that it is not working because some other service (like Apache) is running on this port.
So either fixing privileges or services or changing the port should make it run.

Running manage.py on Heroku for Flask app gives "could not connect"

I am trying to migrate my database on Heroku using heroku run python manage.py db migrate on my Flask app. But I am getting this error:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection
refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
Here is the code to my manage.py file:
import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import create_app, db
app=create_app()
with app.app_context():
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
Here is the configuration file to the database:
import os
class Config:
SECRET_KEY= os.environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI= os.environ.get('SQLALCHEMY_DATABASE_URI')
MAIL_SERVER='smtp.googlemail.com'
MAIL_PORT=587
MAIL_USE_TLS = True
MAIL_USERNAME= os.environ.get('EMAIL_USER')
MAIL_PASSWORD= os.environ.get('EMAIL_PASS')
I have set up the sqlalchemy_database_uri to a database in PostgreSQL in this format postgres://YourUserName:YourPassword#YourHost:5432/YourDatabase.
This error has been bugging me and I cannot find a solution anywhere.
Why isn't this working?
You can't connect your Heroku application to your local database without some major drawbacks. It's a huge pain to set up (you'll need to deal with port forwarding and likely at least one firewall, probably dynamic IP addresses, ...) and your application won't run if your laptop is off.
A better solution would be to have a database in the cloud, and given that you are already using Heroku and PostgreSQL the most natural choice is Heroku's own Postgres service. If you're depending on psycopg2, there's a good chance that one has already been provisioned for you.
If it has, you'll see a DATABASE_URL environment variable containing your connection string. Simply set your SQLAlchemy database URI from that:
SQLALCHEMY_DATABASE_URI= os.environ.get('DATABASE_URL')
If a database hasn't been provisioned for you (check by running heroku addons) you can provision one using the free tier easily:
heroku addons:create heroku-postgresql:hobby-dev
Note that you shouldn't be running manage.py db migrate on Heroku at all. This generates migration files, which will be lost on Heroku's ephemeral filesystem. Generate migrations locally, and commit the migration files. You'll want to run manage.py db upgrade in both places, though.

How to setup psycopg2 with Google App Engine PostgreSQL database

I have an application that is being run on Google's App Engine and I want it to use the associated PostgreSQL database. I'm using psycopg2 to help me with my SQL queries. However I am not sure how I can set up the connection. This is what I currently have:
con = psycopg2.connect(
host=HOST_NAME, # the IP address of the SQL database
database=DATABASE_NAME, # the name of the database (I'm using the default, so this is "postgres"
user=USER_NAME, # just the user name that I created
password=PASSWORD # the password associated to that user
)
However, when I try to make a request, I get the error psycopg2.OperationalError: could not connect to server: Connection timed out when creating this connection. Is there something I am missing?
It is a little bit tricky, but here is what worked for me. I will help you to set up the Quickstart App Engine with psycopg2 and after that you will get the idea.
Use the Quickstart for Python in the App Engine Flexible Environment documentation to set up and deploy your app.
Use the Connecting from App Engine documentation to connect to your App Engine app to the Cloud SQL Postgre SQL.
I have did slightly modifications in order to make that work:
In app.yaml add:
beta_settings:
cloud_sql_instances: [INSTANCE_CONNECTION_NAME]=tcp:5432
#[INSTANCE_CONNECTION_NAME] = [PROJECT_NAME]:[INSTANCE_ZONE]:[INSTANCE_NAME]
#[INSTANCE_CONNECTION_NAME] can be found at Google Cloud Console Cloud SQL's instance page, under "Instance connection name".
In requirements.txt add:
psycopg2
psycopg2-binary
In main.py add:
#app.route('/connect')
def connect():
try:
#host='172.17.0.1' is the defult IP for the docker container that it is being created during the deployment of the App Engine
conn = psycopg2.connect("dbname='postgres' user='postgres' host='172.17.0.1' password='test'")
return "Connection was established!"
except:
return "I am unable to connect to the database"
Use the gcloud app deploy command to deploy your app.
After the deployment, use the gcloud app browse command to open the app in the browser.
When accessing the link https://[PROJECT_ID].appspot.com/connect
It should respond with Connection was established!

mongodb refusing connection in python

I am using windows8, for writing code I use IDLE. I tried to connect python to mongodb. But when trying to get collection name than it gives an error.
ServerSelectionTimeoutError: localhost:20101: [Errno 10061] No connection could be made because the target machine actively refused it
This is code for which i am getting an error.
from pymongo import MongoClient
connection = MongoClient('localhost',20101)
db = connection['Bhautik']
collection = db['Student']
db.collection_names(include_system_collections=True)
By the output message you probably didn't set your mongo bind_ip or didn't set the dbpath. Try this:
mongod --dbpath <database_path> --bind_ip 127.0.0.1 --port 20101
It would be more helpful to put alongside with your code some information regarding the mongodb configuration, like the server port, if you are using authentication or not, which dbpath you are using and so on.
So put in your question your mongodb.conf (if you are using one) or the command you are using to start the mongo server.
If you are starting to use mongoDB after installation, make C:/data/db because it is a default database directory which mongoDB uses.
To change the database directory, do type below:
C:\Program Files\MongoDB\Server\3.x\bin> mongod --dbpath "c:\custom_folder"
You can try
run mongo like that:
"C:\\Program Files\\MongoDB\\Server\\3.6\\bin\\mongod.exe" --dbpath E:\\data\\db --port 27017 --bind_ip 127.0.0.1
E:\data\db should be your location path
then in you code
it will lok like
client = MongoClient("127.0.0.1", 27017)
db = client['addsome']
datas = db.follow_up
and if you want to access from a distant machine make sure you open the port "27017" in the firewall
Some times it's gives this error when you forgot to run the local server (if it's run with local server).
To run it you need to write on your terminal:
mongod
or, if MongoDB not in PATH, you can find it via this link in your computer:
C:\Program Files\MongoDB\Server\4.0\bin\mongod.exe
In order to run MongoDB,
You should have installed MongoDB into your OS, download it from https://www.mongodb.com/download-center/community?tck=docs_server
Add the installation's bin folder to your system environment variables.
Openup the terminal and check 'mongod' and 'mongo' commands are working.
Then try to rerun your python script.

Using python-memcached and the Pyramid Framework Pserve Server

My web application uses the Pyramid framework, and runs on a Debian Linux system. I'm adding python-memcached to the application but cannot get the objects to be stored and retrieved. I get a null value when I retrieve a object from memcached using the key I used to set it with. The testing/debugging server I am using is the Pyramid Framework pserve server.
import memcache
mc = memcache.Client(['127.0.0.1:6543'], debug=0)
mc.set('key1', 'value1', 10)
val = mc.get('key1')
The val is equal to 'null'.
The command I use to run the application is:
$ pserve development.ini --reload
I doubt your memcache server is being run on port 6543 -- assuming you're using the default pyramid config file, your development server is running on port 6543, your memcache server is probably on port 11211. Try running the memcache server and then set
mc = memcache.Client(['127.0.0.1:11211'], debug=0)

Categories