简体   繁体   中英

using Flask, python and postgresql how can I connect to a pre-existing database?

I want to connect to a pre-existing postgres database which has no models associated with it in my app. Unsurprisingly perhaps, this is proving troublesome added to which this is my first attempt with Python and Flask.

The app/py code is:

import os
from flask import Flask
from flask import render_template
from flask.ext.sqlalchemy import SQLAlchemy  
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://blah:blah@ec2-54-227-254-13.compute-1.amazonaws.com:5432/mydb'
db = SQLAlchemy(app)
db.create_all()
db.session.commit()

@app.route("/")
def main():
    return render_template('index.html')


@app.route('/base')
def base():
    myusers = users.all()
    return render_template('base.html')

if __name__ == '__main__':
    app.run(debug=True)

the def main() works so that much I have achieved.

In the view (base.html) we have:

{% for user in myusers %}
    <div><p>{{ user.first_name }} </b></p></div>
    {% endfor %}

When I go to the base.html page the persistent error is NameError: global name 'users' is not defined

What, of many things probably, am I doing wrong here? All help appreciated. Thank you.

You need to reverse engineer your existing database to generate the python models that SQLAlchemy can use.

sqlacodegen can do it for you, install it using pip - pip install sqlacodegen

From the command prompt you can generate your models with the following:

sqlacodegen --outfile c:/temp/models.py postgres://blah:blah@ec2-54-227-254-13.compute-1.amazonaws.com:5432/mydb

Copy the generated models.py file into your project folder and don't forget to import the model classes you need, eg your User class.

Check the models.py file to see how the tables were converted into classes and especially the casing of the generated class names - eg "User" or "user".

You need to pass the "myusers" variable to your template, assuming the generated user class in models.py is called "User":

@app.route('/base')
def base():
    myusers = db.session.query(User).all()
    return render_template('base.html', myusers=myusers)

Don't forget to import the user model at the top of the app.py file (you need to check the name of the user class that was generated by sqlacodgen):

from models import User

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM