From 86e9993f957107b6966c2c44ff791bf32d0d335c Mon Sep 17 00:00:00 2001 From: ashwin1111 Date: Mon, 20 Jul 2020 14:18:51 +0530 Subject: [PATCH 1/3] Base commit - skeleton --- .gitignore | 215 +++++++----- .pylintrc | 585 +++++++++++++++++++++++++++++++++ Dockerfile | 25 ++ fyle_intacct_api/__init__.py | 0 fyle_intacct_api/asgi.py | 16 + fyle_intacct_api/exceptions.py | 21 ++ fyle_intacct_api/settings.py | 197 +++++++++++ fyle_intacct_api/urls.py | 24 ++ fyle_intacct_api/utils.py | 15 + fyle_intacct_api/wsgi.py | 16 + manage.py | 21 ++ requirements.txt | 15 + run.sh | 11 + setup_template.sh | 25 ++ 14 files changed, 1096 insertions(+), 90 deletions(-) create mode 100644 .pylintrc create mode 100644 Dockerfile create mode 100644 fyle_intacct_api/__init__.py create mode 100644 fyle_intacct_api/asgi.py create mode 100644 fyle_intacct_api/exceptions.py create mode 100644 fyle_intacct_api/settings.py create mode 100644 fyle_intacct_api/urls.py create mode 100644 fyle_intacct_api/utils.py create mode 100644 fyle_intacct_api/wsgi.py create mode 100644 manage.py create mode 100644 requirements.txt create mode 100644 run.sh create mode 100644 setup_template.sh diff --git a/.gitignore b/.gitignore index 67045665..8f6538f9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,104 +1,139 @@ -# Logs -logs +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# IDEs +.idea +.vscode + +# Cache +demo_cache.sqlite + +# Setup File +setup.sh + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: *.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -lerna-debug.log* - -# Diagnostic reports (https://nodejs.org/api/report.html) -report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage -*.lcov +local_settings.py +db.sqlite3 +db.sqlite3-journal -# nyc test coverage -.nyc_output +# Flask stuff: +instance/ +.webassets-cache -# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) -.grunt +# Scrapy stuff: +.scrapy -# Bower dependency directory (https://bower.io/) -bower_components +# Sphinx documentation +docs/_build/ -# node-waf configuration -.lock-wscript +# PyBuilder +target/ -# Compiled binary addons (https://nodejs.org/api/addons.html) -build/Release +# Jupyter Notebook +.ipynb_checkpoints -# Dependency directories -node_modules/ -jspm_packages/ +# IPython +profile_default/ +ipython_config.py -# TypeScript v1 declaration files -typings/ +# pyenv +.python-version -# TypeScript cache -*.tsbuildinfo +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock -# Optional npm cache directory -.npm +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ -# Optional eslint cache -.eslintcache +# Celery stuff +celerybeat-schedule +celerybeat.pid -# Microbundle cache -.rpt2_cache/ -.rts2_cache_cjs/ -.rts2_cache_es/ -.rts2_cache_umd/ +# SageMath parsed files +*.sage.py -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# dotenv environment variables file +# Environments .env -.env.test - -# parcel-bundler cache (https://parceljs.org/) -.cache - -# Next.js build output -.next - -# Nuxt.js build / generate output -.nuxt -dist - -# Gatsby files -.cache/ -# Comment in the public line in if your project uses Gatsby and *not* Next.js -# https://nextjs.org/blog/next-9-1#public-directory-support -# public - -# vuepress build output -.vuepress/dist - -# Serverless directories -.serverless/ - -# FuseBox cache -.fusebox/ - -# DynamoDB Local files -.dynamodb/ - -# TernJS port file -.tern-port +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 00000000..0ee28d26 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,585 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-whitelist= + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the blacklist. The +# regex matches against base names, not paths. +ignore-patterns= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Specify a configuration file. +#rcfile= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=print-statement, + parameter-unpacking, + unpacking-in-except, + old-raise-syntax, + backtick, + long-suffix, + old-ne-operator, + old-octal-literal, + import-star-module-level, + non-ascii-bytes-literal, + raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + apply-builtin, + basestring-builtin, + buffer-builtin, + cmp-builtin, + coerce-builtin, + execfile-builtin, + file-builtin, + long-builtin, + raw_input-builtin, + reduce-builtin, + standarderror-builtin, + unicode-builtin, + xrange-builtin, + coerce-method, + delslice-method, + getslice-method, + setslice-method, + no-absolute-import, + old-division, + dict-iter-method, + dict-view-method, + next-method-called, + metaclass-assignment, + indexing-exception, + raising-string, + reload-builtin, + oct-method, + hex-method, + nonzero-method, + cmp-method, + input-builtin, + round-builtin, + intern-builtin, + unichr-builtin, + map-builtin-not-iterating, + zip-builtin-not-iterating, + range-builtin-not-iterating, + filter-builtin-not-iterating, + using-cmp-argument, + eq-without-hash, + div-method, + idiv-method, + rdiv-method, + exception-message-attribute, + invalid-str-codec, + sys-max-int, + bad-python3-import, + deprecated-string-function, + deprecated-str-translate-call, + deprecated-itertools-function, + deprecated-types-field, + next-method-defined, + dict-items-not-iterating, + dict-keys-not-iterating, + dict-values-not-iterating, + deprecated-operator-function, + deprecated-urllib-function, + xreadlines-attribute, + deprecated-sys-function, + exception-escape, + comprehension-escape, + no-self-use, + unused-argument, + invalid-name, + missing-docstring, + too-many-return-statements, + no-else-raise, + inconsistent-return-statements, + duplicate-code, + no-else-return, + no-member, + simplifiable-if-expression, + broad-except, + too-many-arguments, + too-many-locals, + too-few-public-methods + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[REPORTS] + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit + + +[LOGGING] + +# Format style used to check logging format string. `old` means using % +# formatting, while `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it working +# install python-enchant package.. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to indicated private dictionary in +# --spelling-private-dict-file option instead of raising a message. +spelling-store-unknown-words=no + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis. It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=120 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# List of optional constructs for which whitespace checking is disabled. `dict- +# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. +# `trailing-comma` allows a space between comma and closing bracket: (a, ). +# `empty-line` allows space-only lines. +no-space-check=trailing-comma, + dict-separator + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[SIMILARITIES] + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. +#class-attribute-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. +#variable-rgx= + + +[STRING] + +# This flag controls whether the implicit-str-concat-in-sequence should +# generate a warning on implicit string concatenation in sequences defined over +# several lines. +check-str-concat-over-line-jumps=no + + +[IMPORTS] + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules=optparse,tkinter.tix + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled). +ext-import-graph= + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled). +import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[DESIGN] + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement. +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=20 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..6f95db7a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +# Pull python base image +FROM python:3.7.4-slim + +# set environment variables +ENV PYTHONDONTWRITEBYTECODE 1 +ENV PYTHONUNBUFFERED 1 + +# Installing requirements +COPY requirements.txt /tmp/requirements.txt +RUN pip install --upgrade pip && pip install -r /tmp/requirements.txt && pip install pylint-django + + +# Copy Project to the container +RUN mkdir -p /fyle-intacct-api +COPY . /fyle-intacct-api/ +WORKDIR /fyle-intacct-api + +# Do linting checks +RUN pylint --load-plugins pylint_django --rcfile=.pylintrc **/**.py + +# Expose development port +EXPOSE 8000 + +# Run development server +CMD /bin/bash run.sh diff --git a/fyle_intacct_api/__init__.py b/fyle_intacct_api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/fyle_intacct_api/asgi.py b/fyle_intacct_api/asgi.py new file mode 100644 index 00000000..f603efd9 --- /dev/null +++ b/fyle_intacct_api/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for fyle_intacct_api project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fyle_intacct_api.settings') + +application = get_asgi_application() diff --git a/fyle_intacct_api/exceptions.py b/fyle_intacct_api/exceptions.py new file mode 100644 index 00000000..1bd7ec3b --- /dev/null +++ b/fyle_intacct_api/exceptions.py @@ -0,0 +1,21 @@ +""" +Exceptions +""" + + +class BulkError(Exception): + """ + Bulk Error Exception. + + Parameters: + msg (str): Short description of the error. + response: Error response. + """ + + def __init__(self, msg, response=None): + super(BulkError, self).__init__(msg) + self.message = msg + self.response = response + + def __str__(self): + return repr(self.message) diff --git a/fyle_intacct_api/settings.py b/fyle_intacct_api/settings.py new file mode 100644 index 00000000..e882f3b5 --- /dev/null +++ b/fyle_intacct_api/settings.py @@ -0,0 +1,197 @@ +""" +Django settings for fyle_intacct_api project. + +Generated by 'django-admin startproject' using Django 3.0.2. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.0/ref/settings/ +""" +import sys +import os + +import dj_database_url + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = os.environ.get('SECRET_KEY') +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True if os.environ.get('DEBUG') == 'True' else False + +ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS').split(',') + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + + # Installed Apps + 'rest_framework', + 'corsheaders', + 'fyle_rest_auth', + 'fyle_accounting_mappings', + + # User Created Apps + 'apps.users', + 'apps.workspaces', + 'apps.fyle', + 'apps.sage_intacct', + 'apps.tasks' +] + +MIDDLEWARE = [ + 'request_logging.middleware.LoggingMiddleware', + 'corsheaders.middleware.CorsMiddleware', + 'django.middleware.common.CommonMiddleware', + 'corsheaders.middleware.CorsPostCsrfMiddleware', + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'fyle_intacct_api.urls' +APPEND_SLASH = False + +AUTH_USER_MODEL = 'users.User' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +FYLE_REST_AUTH_SERIALIZERS = { + 'USER_DETAILS_SERIALIZER': 'apps.users.serializers.UserSerializer' +} + +REST_FRAMEWORK = { + 'DEFAULT_PERMISSION_CLASSES': ( + 'rest_framework.permissions.IsAuthenticated', + 'apps.workspaces.permissions.WorkspacePermissions' + ), + 'DEFAULT_AUTHENTICATION_CLASSES': ( + 'fyle_rest_auth.authentication.FyleJWTAuthentication', + ), + 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', + 'PAGE_SIZE': 100 +} + +WSGI_APPLICATION = 'fyle_intacct_api.wsgi.application' + + +LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', + 'stream': sys.stderr + }, + }, + 'loggers': { + 'django.request': { + 'handlers': ['console'], + 'level': 'ERROR', + 'propagate': False, + }, + }, +} + +# Database +# https://docs.djangoproject.com/en/3.0/ref/settings/#databases +if os.environ.get('DATABASE_URL', ''): + DATABASES = { + 'default': dj_database_url.config() + } +else: + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'OPTIONS': { + 'options': '-c search_path={0}'.format(os.environ.get('DB_SCHEMA')) + }, + 'NAME': os.environ.get('DB_NAME'), + 'USER': os.environ.get('DB_USER'), + 'PASSWORD': os.environ.get('DB_PASSWORD'), + 'HOST': os.environ.get('DB_HOST'), + 'PORT': os.environ.get('DB_PORT') + } + } + + +# Password validation +# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/3.0/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.0/howto/static-files/ + +STATIC_URL = '/static/' + +# Fyle Settings +API_URL = os.environ.get('API_URL') +FYLE_TOKEN_URI = os.environ.get('FYLE_TOKEN_URI') +FYLE_CLIENT_ID = os.environ.get('FYLE_CLIENT_ID') +FYLE_CLIENT_SECRET = os.environ.get('FYLE_CLIENT_SECRET') +FYLE_BASE_URL = os.environ.get('FYLE_BASE_URL') +FYLE_JOBS_URL = os.environ.get('FYLE_JOBS_URL') +# Sage Intacct Settings +SI_SENDER_ID = os.environ.get('SI_SENDER_ID') +SI_SENDER_PASSWORD = os.environ.get('SI_SENDER_PASSWORD') + +CORS_ORIGIN_ALLOW_ALL = True diff --git a/fyle_intacct_api/urls.py b/fyle_intacct_api/urls.py new file mode 100644 index 00000000..1768092b --- /dev/null +++ b/fyle_intacct_api/urls.py @@ -0,0 +1,24 @@ +"""fyle_intacct_api URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import include, path + +urlpatterns = [ + path('api/admin/', admin.site.urls), + path('api/auth/', include('fyle_rest_auth.urls')), + path('api/workspaces/', include('apps.workspaces.urls')), + path('api/user/', include('apps.users.urls')) +] diff --git a/fyle_intacct_api/utils.py b/fyle_intacct_api/utils.py new file mode 100644 index 00000000..fe007608 --- /dev/null +++ b/fyle_intacct_api/utils.py @@ -0,0 +1,15 @@ +from rest_framework.views import Response +from rest_framework.serializers import ValidationError + + +def assert_valid(condition: bool, message: str) -> Response or None: + """ + Assert conditions + :param condition: Boolean condition + :param message: Bad request message + :return: Response or None + """ + if not condition: + raise ValidationError(detail={ + 'message': message + }) diff --git a/fyle_intacct_api/wsgi.py b/fyle_intacct_api/wsgi.py new file mode 100644 index 00000000..27e8eb95 --- /dev/null +++ b/fyle_intacct_api/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for fyle_intacct_api project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fyle_intacct_api.settings') + +application = get_wsgi_application() diff --git a/manage.py b/manage.py new file mode 100644 index 00000000..7a997018 --- /dev/null +++ b/manage.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fyle_intacct_api.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..33ddd923 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,15 @@ +dj-database-url==0.5.0 +Django==3.0.3 +django-cors-headers==3.2.0 +django-picklefield==3.0.1 +django-request-logging==0.7.1 +django-rest-framework==0.1.0 +djangorestframework==3.11.0 +future==0.18.2 +fyle_accounting_mappings==0.2.0 +fyle-rest-auth==0.4.0 +fylesdk==0.19.0 +psycopg2-binary==2.8.4 +sageintacctsdk==0.2.0 +requests==2.22.0 +six==1.13.0 diff --git a/run.sh b/run.sh new file mode 100644 index 00000000..3c307acc --- /dev/null +++ b/run.sh @@ -0,0 +1,11 @@ +#!/bin/bash + + +# Setting environment variables +source setup.sh + +# Run db migrations +python manage.py migrate + +# Running development server +python manage.py runserver 0.0.0.0:8000 diff --git a/setup_template.sh b/setup_template.sh new file mode 100644 index 00000000..3b63d440 --- /dev/null +++ b/setup_template.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +# Django Settings +export SECRET_KEY=YOUR DJANGO SECRET KEY +export ALLOWED_HOSTS=HOSTS SEPARATED BY COMMAS +export DEBUG=True + +# Database Settings +export DB_NAME=POSTGRES DB NAME +export DB_USER=POSTGRES DB USER +export DB_PASSWORD=POSTGRES DB PASSWORD +export DB_SCHEMA=POSTGRES DB SCHEMA +export DB_PORT=POSTGRES DB PORT + +# Fyle Settings +export FYLE_BASE_URL=FYLE BASE URL +export FYLE_CLIENT_ID=FYLE CLIENT ID +export FYLE_CLIENT_SECRET=FYLE CLIENT SECRET +export FYLE_TOKEN_URI=FYLE TOKEN URI +export FYLE_JOBS_URL=FYLE JOBS URL + +# Sage Intacct Settings +export SI_USER_ID=SAGE INTACCT USER ID +export SI_COMPANY_ID=SAGE INTACCT COMPANY ID +export SI_USER_PASSWORD=SAGE INTACCT USER PASSWORD \ No newline at end of file From 6039a55b146ba0635b08cd29fe6f9512be7c51e8 Mon Sep 17 00:00:00 2001 From: ashwin1111 Date: Mon, 20 Jul 2020 14:20:47 +0530 Subject: [PATCH 2/3] minor change on setup template --- setup_template.sh | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/setup_template.sh b/setup_template.sh index 3b63d440..1c45343d 100644 --- a/setup_template.sh +++ b/setup_template.sh @@ -20,6 +20,5 @@ export FYLE_TOKEN_URI=FYLE TOKEN URI export FYLE_JOBS_URL=FYLE JOBS URL # Sage Intacct Settings -export SI_USER_ID=SAGE INTACCT USER ID -export SI_COMPANY_ID=SAGE INTACCT COMPANY ID -export SI_USER_PASSWORD=SAGE INTACCT USER PASSWORD \ No newline at end of file +export SI_SENDER_ID=SAGE INTACCT SENDER ID +export SI_SENDER_PASSWORD=SAGE INTACCT SENDER PASSWORD From ed69ebd8e983dcc34d0c278ee9169d8bd212798d Mon Sep 17 00:00:00 2001 From: ashwin1111 Date: Mon, 20 Jul 2020 16:41:38 +0530 Subject: [PATCH 3/3] readme changes --- README.md | 63 ++++++++++++++++++++++++++++++++++-- fyle_intacct_api/settings.py | 1 + 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9da67734..2cf8911c 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,61 @@ -# fyle-intacct-api -API Repository for Fyle <> Sage Intacct Integration +# Fyle Sage Intacct API +Django Rest Framework API for Fyle Sage Intacct Integration + + +### Setup + +* Rename setup_template.sh to setup.sh + + ``` + $ mv setup_template.sh setup.sh + ``` + +* Setup environment variables in setup.sh + + ```bash + # Django Settings + export SECRET_KEY=YOUR DJANGO SECRET KEY + export ALLOWED_HOSTS=HOSTS SEPARATED BY COMMAS + export DEBUG=True + + # Database Settings + export DB_NAME=POSTGRES DB NAME + export DB_USER=POSTGRES DB USER + export DB_PASSWORD=POSTGRES DB PASSWORD + export DB_HOST=POSTGRES DB + export DB_PORT=POSTGRES DB PORT + + # Fyle Settings + export FYLE_BASE_URL=FYLE BASE URL + export FYLE_CLIENT_ID=FYLE CLIENT ID + export FYLE_CLIENT_SECRET=FYLE CLIENT SECRET + export FYLE_TOKEN_URI=FYLE TOKEN URI + + # Sage Intacct Settings + export SI_SENDER_ID=SAGE INTACCT SENDER ID + export SI_SENDER_PASSWORD=SAGE INTACCT SENDER PASSWORD + ``` + +* Install the requirements + + ``` + pip install -r requirements.txt + ``` + +* Run the migrations + + ``` + python manage.py migrate + ``` + +* Create superuser + + ``` + python mange.py createsuperuser + ``` + +* run the development server + + ``` + bash run.sh + ``` diff --git a/fyle_intacct_api/settings.py b/fyle_intacct_api/settings.py index e882f3b5..8ac244cb 100644 --- a/fyle_intacct_api/settings.py +++ b/fyle_intacct_api/settings.py @@ -190,6 +190,7 @@ FYLE_CLIENT_SECRET = os.environ.get('FYLE_CLIENT_SECRET') FYLE_BASE_URL = os.environ.get('FYLE_BASE_URL') FYLE_JOBS_URL = os.environ.get('FYLE_JOBS_URL') + # Sage Intacct Settings SI_SENDER_ID = os.environ.get('SI_SENDER_ID') SI_SENDER_PASSWORD = os.environ.get('SI_SENDER_PASSWORD')