Skip to content

Commit 0d01fda

Browse files
added flag for database name, added flag for port, added connection error message, updated README
1 parent f379d19 commit 0d01fda

File tree

2 files changed

+65
-17
lines changed

2 files changed

+65
-17
lines changed

README.md

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,18 @@ A utility script to import data from Star Wars API to a local postgreSQL databas
1313
`git clone https://github.com/ZealousProgramming/swapi-to-postgresql.git`
1414

1515
## Usage
16-
- `HOSTNAME`: `localhost`
17-
- `DATABASE`: The name of the database (DEFAULT: `bootcamp`)
16+
- `DATABASE`: Set the name of the database via the `-db` or `--database` flags
17+
- `PORT_ID`: Set the port to connect to via the `-p` or `--port` flags
1818
- `USERNAME`: An environment variable of the username you use for postgreSQL (DEFAULT: `BOOTCAMP_USER`)
1919
- `PWD`: An environment variable of the password you use for postgreSQL (DEFAULT: `BOOTCAMP_CREDS`)
20-
- `PORT_ID` The port postgreSQL is running on
2120

2221
__Options__:
22+
- `-db, --database`: Name of the database to connect to
23+
- DEFAULT: `bootcamp`
24+
- To change: `-db=some_db` or `--database=some_other_db`
25+
- `-p, --port`: The port to connect to
26+
- DEFAULT: `5432`
27+
- To change: `-p=5433` or `--port=5433`
2328
- `-c, --cache`: Set whether to take advantage of caching
2429
- DEFAULT: `True`
2530
- To disable: `-c=false` or `--cache=false`
@@ -38,6 +43,8 @@ cd swapi-to-postgresql
3843

3944
# In the repo source directory
4045
python ./script.py
46+
python ./script.py -db=some_database # Connect to a db other than `bootcamp`
47+
python ./script.py -p=5433 # Connect to a db on a port other than `5432`
4148
python ./script.py -c=false # Turn off the use of caching
4249
python ./script.py -f # Force a cache update
4350
python ./script.py -v # Produce a detailed output
@@ -55,5 +62,6 @@ python ./script.py --cache=false --verbose
5562
- [x] Format flag
5663
- [x] Syntax error messages for flag setting
5764
- [x] Update documentation to reflect the refactor
58-
- [ ] Flag to use another dbname
59-
- [ ] Flag to use another port
65+
- [x] Flag to use another dbname
66+
- [x] Flag to use another port
67+
- [x] Connection error message

script.py

Lines changed: 52 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from typing import Final
44
from pathlib import Path
55
from sys import argv
6+
import sys
67
import os
78
import json
89
import psycopg2
@@ -11,10 +12,10 @@
1112

1213
# Database info
1314
HOSTNAME: Final[str] = 'localhost'
14-
DATABASE: Final[str] = 'bootcamp'
15+
DATABASE: str = 'bootcamp'
1516
USERNAME: str = os.environ['BOOTCAMP_USER']
1617
PWD: str = os.environ['BOOTCAMP_CREDS']
17-
PORT_ID: Final[str] = '5433'
18+
PORT_ID: str = '5432'
1819

1920
# Options
2021
FORMAT: bool = True
@@ -561,6 +562,8 @@ def print_help():
561562

562563
print('Usage: python ./script.py ([options])')
563564
print('Example:')
565+
print('\tpython ./script.py -db=some_database')
566+
print('\tpython ./script.py -p=5433')
564567
print('\tpython ./script.py -c=false')
565568
print('\tpython ./script.py -f')
566569
print('\tpython ./script.py --cache=false')
@@ -571,13 +574,19 @@ def print_help():
571574
print('\tpython ./script.py --cache=false --verbose')
572575
print('\n')
573576
print('Options:')
574-
print('-c, --cache\t\tWhether or not to cache and use the cached results. Default=true')
577+
print('-db, --database\t\tName of the database to connect to (DEFAULT="bootcamp")')
578+
print('\t\t\t\t-db=some_db')
579+
print('\t\t\t\t-database=some_other_db')
580+
print('-p, --port\t\tThe port to connect to (DEFAULT=5432)')
581+
print('\t\t\t\t-p=5433')
582+
print('\t\t\t\t--port=5434')
583+
print('-c, --cache\t\tWhether or not to cache and use the cached results (Default=true)')
575584
print('\t\t\tDisable caching and the use of any existing cache:')
576-
print('\t\t\t-c=false')
577-
print('\t\t\t--cache=false')
585+
print('\t\t\t\t-c=false')
586+
print('\t\t\t\t--cache=false')
578587
print('-fmt, --format\t\tFormat the fields to be consistent (DEFAULT=true)')
579-
print('\t\t\t-fmt=false')
580-
print('\t\t\t--format=false')
588+
print('\t\t\t\t-fmt=false')
589+
print('\t\t\t\t--format=false')
581590
print('\t\t\tDisable consistency formatting:')
582591
print("-f, --force\t\tForce a cache update")
583592
print('-v, --verbose\t\tPrints out detailed information of the process')
@@ -586,7 +595,7 @@ def print_help():
586595
print('-h, --help\t\tPrint usage information')
587596

588597
async def main():
589-
global VERBOSE, FORCE_CACHE_UPDATE, CACHE, FORMAT
598+
global VERBOSE, FORCE_CACHE_UPDATE, CACHE, FORMAT, DATABASE, PORT_ID
590599
filename: str = 'swapi_data'
591600
bin_location: str = './bin'
592601

@@ -650,7 +659,30 @@ async def main():
650659
elif count > 1:
651660
print('Invalid syntax: Too many = in the flag %s', la)
652661
return
662+
elif arg.startswith('-db=') or arg.startswith('--database='):
663+
count: int = arg.count('=')
653664

665+
if count == 1:
666+
index: int = la.index('=') + 1
667+
value: str = la[index:]
668+
669+
DATABASE = value
670+
671+
elif count > 1:
672+
print('Invalid syntax: Too many = in the flag %s', la)
673+
return
674+
elif arg.startswith('-p=') or arg.startswith('--port='):
675+
count: int = arg.count('=')
676+
677+
if count == 1:
678+
index: int = la.index('=') + 1
679+
value: str = la[index:]
680+
681+
PORT_ID = value
682+
683+
elif count > 1:
684+
print('Invalid syntax: Too many = in the flag %s', la)
685+
return
654686

655687
if FORCE_CACHE_UPDATE and not CACHE:
656688
print('Cannot force a cache update and not have caching enabled.')
@@ -660,6 +692,8 @@ async def main():
660692

661693
if VERBOSE:
662694
print('Running with Options:')
695+
print('\t Database:', DATABASE)
696+
print('\t Database:', PORT_ID)
663697
print('\t Verbose Output:', VERBOSE)
664698
print('\t Formatting:', FORMAT)
665699
print('\t Cache:', CACHE)
@@ -712,7 +746,7 @@ async def main():
712746
print ('Constructing %s table..', category)
713747

714748
if not create_table(cursor, category):
715-
quit(-1)
749+
sys.exit(-1)
716750

717751
print ('Populating tables..')
718752

@@ -721,15 +755,21 @@ async def main():
721755
print ('Populating %s table..', category)
722756

723757
if not populate_table(cursor, category):
724-
quit(-1)
758+
sys.exit(-1)
725759

726760
if VERBOSE:
727761
print(len(DATA[category]), ' records inserted')
728762

729763
connection.commit()
730-
764+
765+
except psycopg2.errors.OperationalError as e:
766+
print("Failed to connect.. \n{0}".format(e))
767+
sys.exit(-1)
768+
731769
except Exception as err:
732-
print('Encountered an error: ', err.__class__.__name__)
770+
# print('Encountered an error: ', err.__class__.__name__)
771+
print('Encountered an error: ', err)
772+
sys.exit(-1)
733773

734774
finally:
735775
if cursor is not None:

0 commit comments

Comments
 (0)