Permalink
Browse files

Adding support for downloading and processing files locally, in case …

…user does not want to use an S3 bucket
  • Loading branch information...
LRParser committed Jul 11, 2018
1 parent de917db commit acd4c09e44820372305b33ac9612db94ea1b9124
@@ -57,7 +57,7 @@ an AWS account is required for S3 usage and performance will be substantially re

c. `$ ./env/bin/pip install -r lexpredict_openedgar/requirements/full.txt`

12. Setup database
12. Setup database. Note that the password chosen for openegar must be set as DJANGO_PASSWORD in the .env later

a. `$ sudo -u postgres createuser -l -P -s openedgar`

@@ -101,7 +101,7 @@ an AWS account is required for S3 usage and performance will be substantially re
$ sudo systemctl status rabbitmq-server.service
```

14. Update .env file
14. Update .env file. For local testing (downloading files locally, instead of to S3), set CLIENT_TYPE to LOCAL and DOWNLOAD_PATH to a local path

a. `$ cp lexpredict_openedgar/sample.env lexpredict_openedgar/.env`

@@ -0,0 +1,46 @@
"""
MIT License
Copyright (c) 2018 ContraxSuite, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

# Libraries
import logging
import os

# Setup logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)

def path_exists(path: str, client=None):
return os.path.exists(path)

def put_buffer(file_path: str, buffer):
dir_name = os.path.dirname(file_path)
if not os.path.exists(dir_name):
os.makedirs(dir_name)
with open(file_path, mode='wb') as localfile:
localfile.write(buffer)
@@ -25,10 +25,11 @@
# Libraries
from typing import Iterable
import logging

import os
# Project
import openedgar.clients.edgar
import openedgar.clients.s3
import openedgar.clients.local
import openedgar.parsers.edgar
from openedgar.models import FilingDocument, SearchQueryTerm, SearchQuery, FilingIndex
from openedgar.tasks import process_filing_index, search_filing_document_sha1
@@ -43,10 +44,11 @@
logger.addHandler(console)


def download_filing_index_data(year: int = None):
def download_filing_index_data(client_type: str = "S3", year: int = None):
"""
Download all filing index data.
:param year:
:param client_type:
:return:
"""
# Get filing index list
@@ -55,45 +57,81 @@ def download_filing_index_data(year: int = None):
else:
filing_index_list = openedgar.clients.edgar.list_index()

# Create S3 client
s3_client = openedgar.clients.s3.get_client()

# Track S3 path lists for return
s3_path_list = []

# Now iterate through list to check if already on S3
for filing_index_path in filing_index_list:
# Cleanup path
if filing_index_path.startswith("/Archives/"):
s3_path = filing_index_path[len("/Archives/"):]
else:
s3_path = filing_index_path

# Check if exists in database
try:
filing_index = FilingIndex.objects.get(edgar_url=filing_index_path)
is_processed = filing_index.is_processed
logger.info("Index {0} already exists in DB.".format(filing_index_path))
except FilingIndex.DoesNotExist:
is_processed = False
logger.info("Index {0} does not exist in DB.".format(filing_index_path))

# Check if exists; download and upload to S3 if missing
if not openedgar.clients.s3.path_exists(s3_path, client=s3_client):
# Download
buffer, _ = openedgar.clients.edgar.get_buffer(filing_index_path)

# Upload
openedgar.clients.s3.put_buffer(s3_path, buffer, client=s3_client)

logger.info("Retrieved {0} and uploaded to S3.".format(filing_index_path))
s3_path_list.append((s3_path, True, is_processed))
else:
logger.info("Index {0} already exists on S3.".format(filing_index_path))
s3_path_list.append((s3_path, False, is_processed))
path_list = []
configured_client = os.environ["CLIENT_TYPE"]
logger.info(msg="Configured client is: {}".format(configured_client))

if configured_client is None or configured_client == "S3":
# Create S3 client
s3_client = openedgar.clients.s3.get_client()

# Now iterate through list to check if already on S3
for filing_index_path in filing_index_list:
# Cleanup path
if filing_index_path.startswith("/Archives/"):
s3_path = filing_index_path[len("/Archives/"):]
else:
s3_path = filing_index_path

# Check if exists in database
try:
filing_index = FilingIndex.objects.get(edgar_url=filing_index_path)
is_processed = filing_index.is_processed
logger.info("Index {0} already exists in DB.".format(filing_index_path))
except FilingIndex.DoesNotExist:
is_processed = False
logger.info("Index {0} does not exist in DB.".format(filing_index_path))

# Check if exists; download and upload to S3 if missing
if not openedgar.clients.s3.path_exists(s3_path, client=s3_client):
# Download
buffer, _ = openedgar.clients.edgar.get_buffer(filing_index_path)

# Upload
openedgar.clients.s3.put_buffer(s3_path, buffer, client=s3_client)

logger.info("Retrieved {0} and uploaded to S3.".format(filing_index_path))
path_list.append((s3_path, True, is_processed))
else:
logger.info("Index {0} already exists on S3.".format(filing_index_path))
path_list.append((s3_path, False, is_processed))

elif configured_client == "LOCAL":

download_path = os.environ["DOWNLOAD_PATH"]

for filing_index_path in filing_index_list:
# Cleanup path
if filing_index_path.startswith("/Archives/"):
file_path = os.path.join(download_path,filing_index_path[len("/Archives/"):])
else:
file_path = os.path.join(download_path,filing_index_path)

# Check if exists in database
try:
filing_index = FilingIndex.objects.get(edgar_url=filing_index_path)
is_processed = filing_index.is_processed
logger.info("Index {0} already exists in DB.".format(filing_index_path))
except FilingIndex.DoesNotExist:
is_processed = False
logger.info("Index {0} does not exist in DB.".format(filing_index_path))

# Check if exists; download and upload to S3 if missing
if not openedgar.clients.local.path_exists(file_path):
# Download
buffer, _ = openedgar.clients.edgar.get_buffer(filing_index_path)

# Upload
openedgar.clients.local.put_buffer(file_path, buffer)

logger.info("Retrieved {0} and stored locally.".format(filing_index_path))
path_list.append((file_path, True, is_processed))
else:
logger.info("Index {0} already exists locally.".format(filing_index_path))
path_list.append((file_path, False, is_processed))

# Return list of updates
return s3_path_list
return path_list


def process_all_filing_index(year: int = None, form_type_list: Iterable[str] = None, new_only: bool = False,
@@ -10,6 +10,9 @@ DJANGO_SECRET_KEY=DJANGO_SECRET_KEY

# General settings
# DJANGO_READ_DOT_ENV_FILE=True
CLIENT_TYPE=LOCAL
DOWNLOAD_PATH=/media/data

DJANGO_ADMIN_URL=
DJANGO_SETTINGS_MODULE=config.settings.production
DJANGO_SECRET_KEY=DJANGO_SECRET_KEY
@@ -39,4 +42,4 @@ S3_SECRET_KEY="abcdefghijklmnopqrstuvwxyz12345678901234"
S3_BUCKET=
S3_DOCUMENT_PATH=documents
S3_PREFIX=data
S3_COMPRESSION_LEVEL=9
S3_COMPRESSION_LEVEL=9

0 comments on commit acd4c09

Please sign in to comment.