Skip to content

Instantly share code, notes, and snippets.

@mathiasbc
Created August 31, 2015 14:56
Show Gist options
  • Save mathiasbc/8a6581bace6c8386abf3 to your computer and use it in GitHub Desktop.
Save mathiasbc/8a6581bace6c8386abf3 to your computer and use it in GitHub Desktop.
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import datetime
# development database credentials
DEV_DB_USER = 'some_user'
DEV_DB_PASSWORD = 'some_password'
DEV_DB_DATABASE = 'database_name'
DEV_DB_HOSTNAME = '10.10.10.10'
# database url
DB_URL = 'mysql://{user}:{passw}@{host}/{database}?charset=utf8'
INSERT_POST = """
INSERT INTO posts
(thread_id, third_party_id, member_name, body, created_at)
VALUES
(:thread_id, :third_party_id, :member_name, :body, :created_at)
ON DUPLICATE KEY UPDATE
thread_id=VALUES(thread_id),
third_party_id=VALUES(third_party_id),
member_name=VALUES(member_name),
body=VALUES(body),
created_at=VALUES(created_at);
"""
INSERT_THREAD = """
INSERT INTO threads
(name, url, created_at, forum_id)
VALUES
(:name, :url, :created_at, :forum_id)
ON DUPLICATE KEY UPDATE
name=VALUES(name),
url=VALUES(url),
created_at=VALUES(created_at),
forum_id=VALUES(forum_id);
"""
DB_URL = DB_URL.format(
user=DEV_DB_USER,
passw=DEV_DB_PASSWORD,
host=DEV_DB_HOSTNAME,
database=DEV_DB_DATABASE
)
#Create and engine and get the metadata
Base = declarative_base()
engine = create_engine(
DB_URL,
pool_recycle=3600,
echo_pool=True,
echo=False
)
metadata = MetaData(bind=engine)
#Create a session to use the tables
Session = sessionmaker(bind=engine)
session = Session()
def insert_to_database(self, content_dict):
now = datetime.datetime.now()
try:
result = session.execute(INSERT_THREAD, {
'name': content_dict['thread_name'],
'url': content_dict['url'],
'created_at': now.strftime('%Y-%m-%d %H:%M:%S'),
'forum_id': 2,
})
session.commit()
session.execute(INSERT_POST, {
'thread_id': 'THREAD ID HERE',
'third_party_id': '', # leave blank
'member_name': 'USERNAME HERE',
'post_id': 'POST ID HERE',
'thread_id': 'THREAD ID INSERTED ABOVE',
'body': 'CONTENT HERE',
'created_at': now.strftime('%Y-%m-%d %H:%M:%S')
})
session.commit()
except Exception as e:
print("[ E ] %s" % e)
session.rollback()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment