TST BUG: We still need OperationalError import

This commit is contained in:
Kelsey Jordahl
2014-07-12 13:52:22 -05:00
parent 457e8e8b5a
commit 04d263ae66
+24 -31
View File
@@ -1,18 +1,9 @@
import io
import os.path
from six.moves.urllib.request import urlopen
from sqlalchemy import create_engine
from geopandas import GeoDataFrame, GeoSeries
try:
from pandas import read_sql_table
except ImportError:
PANDAS_NEW_SQL_API = False
else:
PANDAS_NEW_SQL_API = True
# Compatibility layer for Python 2.6: try loading unittest2
import sys
if sys.version_info[:2] == (2, 6):
@@ -24,6 +15,20 @@ if sys.version_info[:2] == (2, 6):
else:
import unittest
try:
import psycopg2
from psycopg2 import OperationalError
except ImportError:
class OperationalError(Exception):
pass
try:
from pandas import read_sql_table
except ImportError:
PANDAS_NEW_SQL_API = False
else:
PANDAS_NEW_SQL_API = True
def download_nybb():
""" Returns the path to the NYC boroughs file. Downloads if necessary. """
@@ -52,17 +57,12 @@ def validate_boro_df(test, df):
def connect(dbname):
try:
if PANDAS_NEW_SQL_API:
driver = 'psycopg2'
conn_str = 'postgresql+{driver}://localhost/{dbname}'
engine = create_engine(conn_str.format(driver=driver, dbname=dbname))
return engine
else:
con = psycopg2.connect(dbname=dbname)
return con
con = psycopg2.connect(dbname=dbname)
except (NameError, OperationalError):
return None
return con
def create_db(df):
"""
@@ -77,22 +77,13 @@ def create_db(df):
# 'test_geopandas' and enable postgis in it:
# > createdb test_geopandas
# > psql -c "CREATE EXTENSION postgis" -d test_geopandas
try:
con = connect('test_geopandas')
except:
return False
con = connect('test_geopandas')
if con is None:
return False
if PANDAS_NEW_SQL_API:
try:
con = con.connect()
except:
return False
else:
con = con.cursor()
try:
con.execute("DROP TABLE IF EXISTS nybb;")
cursor = con.cursor()
cursor.execute("DROP TABLE IF EXISTS nybb;")
sql = """CREATE TABLE nybb (
geom geometry,
@@ -101,18 +92,20 @@ def create_db(df):
shape_leng float,
shape_area float
);"""
con.execute(sql)
cursor.execute(sql)
for i, row in df.iterrows():
sql = """INSERT INTO nybb VALUES (
ST_GeometryFromText(%s), %s, %s, %s, %s
);"""
con.execute(sql, (row['geometry'].wkt,
cursor.execute(sql, (row['geometry'].wkt,
row['BoroCode'],
row['BoroName'],
row['Shape_Leng'],
row['Shape_Area']))
finally:
cursor.close()
con.commit()
con.close()
return True