2014-05-11 32 views
0

我看了看教程這裏:http://www.pythoncentral.io/introductory-tutorial-python-sqlalchemy/Python導入 - 這些可執行語句是否運行?

我的問題,決定性的部分是第一:

import os 
import sys 
from sqlalchemy import Column, ForeignKey, Integer, String 
from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy.orm import relationship 
from sqlalchemy import create_engine 

Base = declarative_base() 

class Person(Base): 
    __tablename__ = 'person' 
    # Here we define columns for the table person 
    # Notice that each column is also a normal Python instance attribute. 
    id = Column(Integer, primary_key=True) 
    name = Column(String(250), nullable=False) 

class Address(Base): 
    __tablename__ = 'address' 
    # Here we define columns for the table address. 
    # Notice that each column is also a normal Python instance attribute. 
    id = Column(Integer, primary_key=True) 
    street_name = Column(String(250)) 
    street_number = Column(String(250)) 
    post_code = Column(String(250), nullable=False) 
    person_id = Column(Integer, ForeignKey('person.id')) 
    person = relationship(Person) 

# Create an engine that stores data in the local directory's 
# sqlalchemy_example.db file. 
engine = create_engine('sqlite:///sqlalchemy_example.db') 

# Create all tables in the engine. This is equivalent to "Create Table" 
# statements in raw SQL. 
Base.metadata.create_all(engine) 

和第二:

from sqlalchemy import create_engine 
from sqlalchemy.orm import sessionmaker 

from sqlalchemy_declarative import Address, Base, Person 

engine = create_engine('sqlite:///sqlalchemy_example.db') 
# Bind the engine to the metadata of the Base class so that the 
# declaratives can be accessed through a DBSession instance 
Base.metadata.bind = engine 

DBSession = sessionmaker(bind=engine) 
# A DBSession() instance establishes all conversations with the database 
# and represents a "staging zone" for all the objects loaded into the 
# database session object. Any change made against the objects in the 
# session won't be persisted into the database until you call 
# session.commit(). If you're not happy about the changes, you can 
# revert all of them back to the last commit by calling 
# session.rollback() 
session = DBSession() 

# Insert a Person in the person table 
new_person = Person(name='new person') 
session.add(new_person) 
session.commit() 

# Insert an Address in the address table 
new_address = Address(post_code='00000', person=new_person) 
session.add(new_address) 
session.commit() 

如果第二部分是運行(例如, 「python second_part」),不會導入語句

from sqlalchemy_declarative import Address, Base, Person 

導致第一部分中的所有可執行代碼都運行? (這將觸發其在數據庫創建表的每個第一部分運行時的代碼)

問候

回答

0

是的,每一個,第一個文件是進口的,再次創建表的時間。

爲了防止這種情況,使用下面的語句:

if __name__ == '__main__': 
    Base.metadata.create_all(engine)