def config(name='DATABASE_URL', default='sqlite://:memory:'): """Returns configured DATABASE dictionary from DATABASE_URL.""" config = {} s = env(name, default) if s: config = parse_database_url(s) return config
def config(name='CACHE_URL', default='locmem://'): """Returns configured CACHES dictionary from CACHE_URL""" config = {} s = env(name, default) if s: config = parse_cache_url(s) return config
def borgcollector_harvest(request, publishes=['prs_locations']): """Convenience function to manually run a Borg Collector harvest job for the PRS locations layer. Docs: https://github.com/parksandwildlife/borgcollector """ api_url = env('BORGCOLLECTOR_API', 'https://borg.dpaw.wa.gov.au/api/') + 'jobs/' # Send a POST request to the API endpoint. r = post_sso(user_request=request, url=api_url, data=json.dumps({'publishes': publishes})) return r
def config(name='SEARCH_URL', default='simple://'): """Returns configured SEARCH dictionary from SEARCH_URL""" config = {} s = env(name, default) if s: config = parse_search_url(s) return config
from confy import env, database from oscar.defaults import * from oscar import get_core_apps, OSCAR_MAIN_TEMPLATE_DIR import os # Project paths # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.join(BASE_DIR, 'ledger') # Application definitions SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG', False) CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if not DEBUG: ALLOWED_HOSTS = env('ALLOWED_HOSTS', []) WSGI_APPLICATION = 'ledger.wsgi.application' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.flatpages', 'social.apps.django_app.default', 'django_extensions',
def createCustomBasket(product_list, owner, system, vouchers=None, force_flush=True): ''' Create a basket so that a user can check it out. @param product_list - [ { "id": "<id of the product in oscar>", "quantity": "<quantity of the products to be added>" } ] @param - owner (user id or user object) ''' #import pdb; pdb.set_trace() try: old_basket = basket = None valid_products = [] User = get_user_model() # Check if owner is of class AUTH_USER_MODEL or id if not isinstance(owner, AnonymousUser): if not isinstance(owner, User): owner = User.objects.get(id=owner) # Check if owner has previous baskets open_baskets = Basket.objects.filter(status='Open', system=system, owner=owner).count() if open_baskets > 0: old_basket = Basket.objects.filter(status='Open', system=system, owner=owner)[0] # Use the previously open basket if its present or create a new one if old_basket: if system.lower() == old_basket.system.lower( ) or not old_basket.system: basket = old_basket if force_flush: basket.flush() else: raise ValidationError( 'You have a basket that is not completed in system {}'. format(old_basket.system)) else: basket = Basket() # Set the owner and strategy being used to create the basket if isinstance(owner, User): basket.owner = owner basket.system = system basket.strategy = selector.strategy(user=owner) basket.custom_ledger = True # Check if there are products to be added to the cart and if they are valid products defaults = ('ledger_description', 'quantity', 'price_incl_tax', 'oracle_code') UPDATE_PAYMENT_ALLOCATION = env('UPDATE_PAYMENT_ALLOCATION', False) if UPDATE_PAYMENT_ALLOCATION is True: defaults = ('ledger_description', 'quantity', 'price_incl_tax', 'oracle_code', 'line_status') for p in product_list: if not all(d in p for d in defaults): raise ValidationError( 'Please make sure that the product format is valid') p['price_excl_tax'] = calculate_excl_gst(p['price_incl_tax']) # Save the basket basket.save() # Add the valid products to the basket for p in product_list: basket.addNonOscarProduct(p) # Save the basket (again) basket.save() # Add vouchers to the basket if vouchers is not None: for v in vouchers: basket.vouchers.add(Voucher.objects.get(code=v["code"])) basket.save() return basket except Product.DoesNotExist: raise except Exception as e: raise
""" from __future__ import absolute_import, unicode_literals # import os # from boto.s3.connection import OrdinaryCallingFormat, SubdomainCallingFormat # from django.utils import six from confy import env from .common import * # noqa # SECRET CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ # unless default is set SECRET_KEY = env('DJANGO_SECRET_KEY', default="CHANGEME") # This ensures that Django will be able to detect a secure connection # properly on Heroku. SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Use Whitenoise to serve static files # See: https://whitenoise.readthedocs.io/ # WHITENOISE_MIDDLEWARE = ('whitenoise.middleware.WhiteNoiseMiddleware', ) # MIDDLEWARE_CLASSES = WHITENOISE_MIDDLEWARE + MIDDLEWARE_CLASSES # STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' # SECURITY CONFIGURATION # ------------------------------------------------------------------------------ # See https://docs.djangoproject.com/en/1.9/ref/middleware/#module-django.middleware.security # and https://docs.djangoproject.com/ja/1.9/howto/deployment/checklist/#run-manage-py-check-deploy
from confy import env, database import os import sys from unipath import Path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).ancestor(3) PROJECT_DIR = os.path.join(BASE_DIR, 'biosys') # Add PROJECT_DIR to the system path. sys.path.insert(0, PROJECT_DIR) # Add PROJECT_DIR/apps to the system path. sys.path.insert(0, os.path.join(PROJECT_DIR, 'apps')) # Security settings DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY') CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if not DEBUG: # Localhost, UAT and Production hosts ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'biosys.dpaw.wa.gov.au', 'biosys.dpaw.wa.gov.au.', 'biosys-uat.dpaw.wa.gov.au', 'biosys-uat.dpaw.wa.gov.au.', ]
Tests run by `fab test` explicitly use `sdis/test_settings.py`. """ from confy import env, database, cache import ldap import os import sys from unipath import Path from django_auth_ldap.config import (LDAPSearch, GroupOfNamesType, LDAPSearchUnion) BASE_DIR = Path(__file__).ancestor(2) PROJECT_DIR = os.path.join(BASE_DIR, 'pythia') sys.path.insert(0, PROJECT_DIR) SECRET_KEY = env('SECRET_KEY', default='foo') DEBUG = env('DEBUG', default=False) CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', default=True) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', default=True) GOOGLE_ANALYTICS_KEY = env('GOOGLE_ANALYTICS_KEY', default='') CACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', }} TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'sdis.dpaw.wa.gov.au', 'sdis.dpaw.wa.gov.au.', 'sdis-dev.dpaw.wa.gov.au',
from confy import env, database import os from taskmanagement import settings_base # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_URLCONF = 'taskmanagement.urls' SITE_ID = 1 STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') BOOKING_TIMEOUT = 1200 # Define the following in the environment: DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY') if not DEBUG: ALLOWED_HOSTS = [ env('ALLOWED_DOMAIN'), ] else: ALLOWED_HOSTS = ['*'] GIT_COMMIT_DATE = os.popen('git log -1 --format=%cd').read() # Application definition #AUTH_USER_MODEL = 'accounts.EmailUser' INSTALLED_APPS = [ ### 'reversion', 'crispy_forms', 'bootstrap4', 'webtemplate_dbca',
https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) CRISPY_TEMPLATE_PACK = 'bootstrap3' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! #SECRET_KEY = 'e=#n(l%o-)a3=v(&gf0bcla$ywu$wnw+4a#!usu@nu0+ps%yjv' SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True #ALLOWED_HOSTS = [] INTERNAL_IPS = ['127.0.0.1', '::1'] #if not DEBUG: ## Localhost, UAT and Production hosts #ALLOWED_HOSTS = [ #'localhost', #'127.0.0.1', # ]
def handle(self, *args, **options): confy.read_environment_file() ErrorReportFromEmail = "*****@*****.**" ErrorReportEmail = "*****@*****.**" if env("ERROR_REPORTS_EMAIL"): ErrorReportEmail = env("ERROR_REPORTS_EMAIL") print "DEBUG Notification Email Address: "+ErrorReportEmail VechInfo = FsVehicleDetails.objects.all() for VeIn in VechInfo: print "Checking for Vehicle: "+str(VeIn.vehicle_id) try: VD = VehicleDetails.objects.get(vehicle_id=VeIn.vehicle_id) VD.rego = VeIn.rego VD.make = VeIn.make_desc VD.model = VeIn.model_desc VD.kms = VeIn.kms VD.light_flag = VeIn.light_flag VD.category = VeIn.category_desc VD.rate = VeIn.rate VD.default_job_id = VeIn.default_job_id VD.month_cost = VeIn.month_cost VD.status_flag = VeIn.status_flag VD.cost_centre = VeIn.cost_centre VD.manufactured_month_year = VeIn.manufactured_mth_yr VD.engine_no = VeIn.engine_no VD.diesel_engine = VeIn.diesel_flag VD.automatic_engine = VeIn.automatic_flag VD.tare = VeIn.tare VD.gcm = VeIn.gcm VD.serial_chassis_no = VeIn.serial_chassis_no VD.date_deleted = VeIn.delete_date VD.comments = VeIn.comments VD.comments2 = VeIn.comments2 VD.comments3 = VeIn.comments3 VD.location = VeIn.location VD.save() except: VehicleDetails.objects.create( vehicle_id = VeIn.vehicle_id, rego = VeIn.rego, make = VeIn.make_desc, model = VeIn.model_desc, kms = VeIn.kms, light_flag = VeIn.light_flag, category = VeIn.category_desc, rate = VeIn.rate, default_job_id = VeIn.default_job_id, month_cost = VeIn.month_cost, status_flag = VeIn.status_flag, cost_centre = VeIn.cost_centre, manufactured_month_year = VeIn.manufactured_mth_yr, engine_no = VeIn.engine_no, diesel_engine = VeIn.diesel_flag, automatic_engine = VeIn.automatic_flag, tare = VeIn.tare, gcm = VeIn.gcm, serial_chassis_no = VeIn.serial_chassis_no, date_deleted = VeIn.delete_date, comments = VeIn.comments, comments2 = VeIn.comments2, comments3 = VeIn.comments3, location = VeIn.location ) # ErrorReportEmail = '*****@*****.**' venList = {} assetTypeList = {} supList = {} statusList = {} assetModelList = {} print "Creating Unknown ID fields for Supplier, Locations, Vendors" # Check For Default Data try: supCheck = Suppliers.objects.get(id=0) except Suppliers.DoesNotExist: Suppliers.objects.create(id=0, name='Unknown Supplier' ) try: locCheck = Location.objects.get(id=0) except Location.DoesNotExist: Location.objects.create(id=0, name='Unknown Location', address="Unknown Address" ) try: venCheck = Vendor.objects.get(id=0) except Vendor.DoesNotExist: Vendor.objects.create(id=0, name='Unknown Vendor') print "Creating and Validating Manufactures --> Vendors "; # Manufacturers are Vendor equivelent in OIM. allManU = FsComManufacturers.objects.all() for manu in allManU: # Check if Vendor exists in OIM .. If does not exist create it. assetVen = None try: assetVen = Vendor.objects.get(name=manu.name) except Vendor.DoesNotExist: assetVen = None venCreate = Vendor.objects.create() venCreate.name = manu.name venCreate.save() # Create temport vendor to manufacture map list. allManU = FsComManufacturers.objects.all() for manu in allManU: assetVen = Vendor.objects.get(name=manu.name) venList[manu.mnf_id] = assetVen.id MODEL_TYPE_CHOICES = dict(HardwareModel.TYPE_CHOICES) allAssetsTypes = FsComAssetTypes.objects.all() for AssetType in allAssetsTypes: # print AssetType.name assetTypeList[AssetType.att_id] = 'Comms - '+AssetType.name # print assetTypeList['Comms - '+AssetType.name] try: MODEL_TYPE_CHOICES['Comms - '+AssetType.name] except KeyError: fromaddr = ErrorReportFromEmail toaddr = ErrorReportEmail msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "FC_COM Asset Import Hardware Model Choice Does not Exist" body = "Hello,\n\nALERT:\n\nThe follow hardware model type choice does not exist in OIM Assets:\n\n -> "+AssetType.name+" \n\n Please update the assets.models.py file with the missing model category type.\n\nKind Regards\nOIM-ASI Robot" msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('localhost', 25) server.starttls() text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() allManModels = FsComManufacturerModels.objects.all() for ManModels in allManModels: try: hwModel = HardwareModel.objects.get(model_no=ManModels.name) except HardwareModel.DoesNotExist: print "Model doesn't exist, Trying to Create it: "+ManModels.name hwModelCreate = HardwareModel.objects.create(lifecycle=5, vendor_id=venList[ManModels.mnf_id], model_no=ManModels.name, model_type=assetTypeList[ManModels.att_id]) # Get Model to OIM link Id allManModels = FsComManufacturerModels.objects.all() for ManModels in allManModels: hwModel = HardwareModel.objects.get(model_no=ManModels.name) assetModelList[ManModels.mod_id] = hwModel.id # Suppliers print "Creating and Validating Suppliers" allSuppliers = FsComSuppliers.objects.all() for sup in allSuppliers: try: sipRow = Suppliers.objects.get(name=sup.name) except Suppliers.DoesNotExist: supCreate = Suppliers.objects.create(name=sup.name,address1=sup.address_line_1, address2=sup.address_line_2, address3=sup.address_line_3, suburb=sup.town_suburb,postcode=sup.postcode,state=sup.state, effective_from=sup.effective_from,effective_to=sup.effective_to) # Create Supplier ID match list with FS_COM and OIM allSuppliers = FsComSuppliers.objects.all() supList[0] = '0' for sup in allSuppliers: sipRow = Suppliers.objects.get(name=sup.name) supList[sup.sup_id] = sipRow.id print "Preparing to create FS_COM assets in OIM" allFsComAssets = FsComAssets.objects.all() for fscomasset in allFsComAssets: if fscomasset.sup_id is None: fscomasset.sup_id = 0 ManModels = FsComManufacturerModels.objects.get(mod_id=fscomasset.mod_id) # print "MAN MODEL" # print ManModels.mnf_id # print "===---==========" # # print "---==== NEW RECORD ====---"; # print fscomasset.ast_id # print fscomasset.sup_id # print fscomasset.mod_id # print fscomasset.dec_serial_no # print fscomasset.manufacturer_serial_no # print fscomasset.dec_comms_purchase # print fscomasset.purchase_price_ex_gst # print fscomasset.purchase_order_no # print fscomasset.purchase_date # print fscomasset.warranty_expiry_date # print fscomasset.dec_asset_no # print fscomasset.dec_asset_label_attached # print fscomasset.denorm_asy.name # print fscomasset.comments # print fscomasset.date_modified # print fscomasset.modified_by # print fscomasset.date_created # print fscomasset.created_by # print "============================"; #print fscomasset.extra_data # if fscomasset.dec_asset_no is None: # fscomasset.dec_asset_no = "NOTAG"+str(fscomasset.ast_id) #print "Working" assetexists = 'no' try: getAssetInfo = HardwareAsset.objects.get(rsid=fscomasset.ast_id) # print "--====RSID Exsits===--" # print getAssetInfo.id assetexists = 'yes' getAssetInfo.date_created = fscomasset.date_created getAssetInfo.date_updated = fscomasset.date_modified getAssetInfo.date_purchased = fscomasset.purchase_date getAssetInfo.purchased_value = fscomasset.purchase_price_ex_gst getAssetInfo.asset_tag = fscomasset.dec_serial_no getAssetInfo.finance_asset_tag = fscomasset.dec_asset_no getAssetInfo.status = fscomasset.denorm_asy.name getAssetInfo.serial = fscomasset.manufacturer_serial_no getAssetInfo.hardware_model_id = assetModelList[fscomasset.mod_id] getAssetInfo.invoice_id = None getAssetInfo.location_id = 0 getAssetInfo.org_unit_id = 1 getAssetInfo.vendor_id = venList[ManModels.mnf_id] getAssetInfo.supplier_id = supList[fscomasset.sup_id] getAssetInfo.notes = fscomasset.comments getAssetInfo.rsid = fscomasset.ast_id # rowjsondata = serializers.serialize("json", fscomasset) # getAssetInfo.extra_data = rowjsondata # print toJSON(fscomasset) try: rowjsondata = serializers.serialize("json", [fscomasset,]) getAssetInfo.extra_data = rowjsondata getAssetInfo.save() print "Updated FC_COM --> OIM record: "+str(fscomasset.ast_id) # print "===-=-=-=-= UPDATING RECORD ===-=-=-=" except Exception, d: print "Update Exception sent to: " + ErrorReportEmail fromaddr = "*****@*****.**" toaddr = ErrorReportEmail msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "UPDATE ASSET: Error Importing Asset Record" body = "Hello,\n\nThere was and error importing and asset into OIM. See information below:\n\n[Exception]\n"+str(d)+" \n[Object]" body += "\ndate_created: "+str(fscomasset.date_created) body += "\ndate_updated: "+str(fscomasset.date_modified) body += "\ndate_purchased: "+str(fscomasset.purchase_date) body += "\npurchased_value: "+str(fscomasset.purchase_price_ex_gst) body += "\nasset_tag: "+str(fscomasset.dec_asset_no) body += "\nfinance_asset_tag: "+str(fscomasset.dec_serial_no) body += "\nstatus: "+ str(fscomasset.denorm_asy.name) body += "\nserial: "+ str(fscomasset.manufacturer_serial_no) body += "\nhardware_model_id: "+str(assetModelList[fscomasset.mod_id]) body += "\ninvoice_id: None" body += "\nlocation_id: 0" body += "\norg_unit_id: 1" body += "\nvendor_id: "+ str(venList[ManModels.mnf_id]) body += "\nsupplier_id: "+str(supList[fscomasset.sup_id]) body += "\nnotes: "+fscomasset.comments body += "\nrsid: "+str(fscomasset.ast_id) body += "\n" body += "\nKind Regards\nOIM-ASI Robot" msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('localhost', 25) server.starttls() # server.login(fromaddr, "") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() except Exception, e: assetexists = 'no' # print "exists" # print e if assetexists is 'no': try: rowjsondata = serializers.serialize("json", [fscomasset,]) HWA = HardwareAsset.objects.create( date_created = fscomasset.date_created, date_updated = fscomasset.date_modified, date_purchased = fscomasset.purchase_date, purchased_value = fscomasset.purchase_price_ex_gst, asset_tag = fscomasset.dec_serial_no, finance_asset_tag = fscomasset.dec_asset_no, status = fscomasset.denorm_asy.name, serial = fscomasset.manufacturer_serial_no, hardware_model_id = assetModelList[fscomasset.mod_id], invoice_id = None, location_id = 0, org_unit_id = 1, vendor_id = venList[ManModels.mnf_id], supplier_id = supList[fscomasset.sup_id], notes = fscomasset.comments, rsid = fscomasset.ast_id, extra_data = rowjsondata ) print "New Asset From FC_COM record: "+str(fscomasset.ast_id) except Exception, e: print "New Asset Exception sent to: " + ErrorReportEmail fromaddr = "*****@*****.**" toaddr = ErrorReportEmail msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "NEW ASSET: Error Importing Asset Record" body = "Hello,\n\nThere was and error importing and asset into OIM. See information below:\n\n[Exception]\n"+str(e)+" \n[Object]" body += "\ndate_created: "+str(fscomasset.date_created) body += "\ndate_updated: "+str(fscomasset.date_modified) body += "\ndate_purchased: "+str(fscomasset.purchase_date) body += "\npurchased_value: "+str(fscomasset.purchase_price_ex_gst) body += "\nasset_tag: "+str(fscomasset.dec_asset_no) body += "\nfinance_asset_tag: "+str(fscomasset.dec_serial_no) body += "\nstatus: "+ str(fscomasset.denorm_asy.name) body += "\nserial: "+ str(fscomasset.manufacturer_serial_no) body += "\nhardware_model_id: "+str(assetModelList[fscomasset.mod_id]) body += "\ninvoice_id: None" body += "\nlocation_id: 0" body += "\norg_unit_id: 1" body += "\nvendor_id: "+ str(venList[ManModels.mnf_id]) body += "\nsupplier_id: "+str(supList[fscomasset.sup_id]) body += "\nnotes: "+fscomasset.comments body += "\nrsid: "+str(fscomasset.ast_id) body += "\n" body += "\nKind Regards\nOIM-ASI Robot" msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('localhost', 25) server.starttls() # server.login(fromaddr, "") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit()
""" Django settings for parkourdex project. """ from confy import env, database, cache import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG') if not DEBUG: ALLOWED_HOSTS = env('ALLOWED_HOSTS', '').split(',') else: ALLOWED_HOSTS = ['*'] DEFAULT_FROM_EMAIL = env('DEFAULT_FROM_EMAIL') # Application definition INSTALLED_APPS = [ 'parkourdex', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',
from django.core.exceptions import ImproperlyConfigured from confy import env, database from oscar.defaults import * from oscar import get_core_apps, OSCAR_MAIN_TEMPLATE_DIR import os # Project paths # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.join(BASE_DIR, 'ledger') # Application definitions SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG', False) CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if DEBUG: ALLOWED_HOSTS = ['*'] else: ALLOWED_HOSTS = env('ALLOWED_HOSTS', []) WSGI_APPLICATION = 'ledger.wsgi.application' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles',
from ledger.settings_base import * # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_URLCONF = 'statdev.urls' SITE_ID = 1 STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') BOOKING_TIMEOUT = 1200 JCAPTCHA_EXPIRY_MINUTES = 15 JCAPTCHA_CLEANUP_MINUTES = 100 # Define the following in the environment: DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY') #if not DEBUG: # ALLOWED_HOSTS = [env('ALLOWED_DOMAIN'), ] #else: # ALLOWED_HOSTS = ['*'] #GIT_COMMIT_DATE = os.popen('git log -1 --format=%cd').read() # Application definition #AUTH_USER_MODEL = 'accounts.EmailUser' INSTALLED_APPS += [ ### 'reversion', 'crispy_forms', 'bootstrap3', 'webtemplate_dbca', 'django_q', 'applications',
#!/usr/bin/python from bottle import Bottle, route, static_file, request, response import confy import os import ujson from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session dot_env = os.path.join(os.getcwd(), '.env') if os.path.exists(dot_env): confy.read_environment_file() database_url = confy.env('DATABASE_URL').replace('postgis', 'postgres') engine = create_engine(database_url) Session = scoped_session(sessionmaker(bind=engine, autoflush=True)) app = application = Bottle() @app.route('/') def index(): return static_file('index.html', root='caddy/templates') @app.route('/api/geocode') def geocode(): response.content_type = 'application/json' # Allow cross-origin GET requests. response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS' response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token' q = request.query.q or ''
""" Django settings for statdev project. Generated by 'django-admin startproject' using Django 1.10.5. """ from confy import env, database import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Define the following in the environment: DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY') if not DEBUG: ALLOWED_HOSTS = [ env('ALLOWED_DOMAIN'), ] else: ALLOWED_HOSTS = ['*'] # Application definition AUTH_USER_MODEL = 'accounts.EmailUser' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions',
python manage.py runserver --settings=whatsmyworkout.settings.base """ from confy import env, database import os import sys from unipath import Path # Project paths # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).ancestor(2) PROJECT_DIR = os.path.join(BASE_DIR, 'whatsmyworkout') # Add PROJECT_DIR to the system path. sys.path.insert(0, PROJECT_DIR) # Application definition DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY') ALLOWED_HOSTS = [] ROOT_URLCONF = 'whatsmyworkout.urls' WSGI_APPLICATION = 'whatsmyworkout.wsgi.application' SITE_ID = 1 INSTALLED_APPS = ( 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Third-party apps
from confy import database, env import os import sys from pathlib import Path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = str(Path(__file__).resolve().parents[1]) PROJECT_DIR = str(Path(__file__).resolve().parents[0]) # Add PROJECT_DIR to the system path. sys.path.insert(0, PROJECT_DIR) # Settings defined in environment variables. DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY', 'PlaceholderSecretKey') CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if not DEBUG: ALLOWED_HOSTS = env('ALLOWED_DOMAINS', '').split(',') else: ALLOWED_HOSTS = ['*'] INTERNAL_IPS = ['127.0.0.1', '::1'] ROOT_URLCONF = 'ibms_project.urls' WSGI_APPLICATION = 'ibms_project.wsgi.application' INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django_extensions',
def sendHtmlEmail(to,subject,context,template,cc,bcc,from_email,template_group,attachments=None): email_delivery = env('EMAIL_DELIVERY', 'off') override_email = env('OVERRIDE_EMAIL', None) context['default_url'] = env('DEFAULT_HOST', '') context['default_url_internal'] = env('DEFAULT_URL_INTERNAL', '') if email_delivery != 'on': print ("EMAIL DELIVERY IS OFF NO EMAIL SENT -- email.py ") return False if template is None: raise ValidationError('Invalid Template') if to is None: raise ValidationError('Invalid Email') if subject is None: raise ValidationError('Invalid Subject') if from_email is None: if settings.DEFAULT_FROM_EMAIL: from_email = settings.DEFAULT_FROM_EMAIL else: from_email = '*****@*****.**' context['version'] = settings.VERSION_NO # Custom Email Body Template context['body'] = get_template(template).render(Context(context)) # Main Email Template Style ( body template is populated in the center if template_group == 'rottnest': main_template = get_template('mooring/email/base_email-rottnest.html').render(Context(context)) else: main_template = get_template('mooring/email/base_email2.html').render(Context(context)) reply_to=None if attachments is None: attachments = [] # Convert Documents to (filename, content, mime) attachment _attachments = [] for attachment in attachments: if isinstance(attachment, Document): filename = str(attachment) content = attachment.file.read() mime = mimetypes.guess_type(attachment.filename)[0] _attachments.append((filename, content, mime)) else: _attachments.append(attachment) if override_email is not None: to = override_email.split(",") if cc: cc = override_email.split(",") if bcc: bcc = override_email.split(",") if len(to) > 1: for to_email in to: msg = EmailMultiAlternatives(subject, "Please open with a compatible html email client.", from_email=from_email, to=to_email, attachments=_attachments, cc=cc, bcc=bcc, reply_to=reply_to) msg.attach_alternative(main_template, 'text/html') #msg = EmailMessage(subject, main_template, to=[to_email],cc=cc, from_email=from_email) #msg.content_subtype = 'html' #if attachment1: # for a in attachment1: # msg.attach(a) msg.send() else: msg = EmailMultiAlternatives(subject, "Please open with a compatible html email client.", from_email=from_email, to=to, attachments=_attachments, cc=cc, bcc=bcc, reply_to=reply_to) msg.attach_alternative(main_template, 'text/html') #msg = EmailMessage(subject, main_template, to=to,cc=cc, from_email=from_email) #msg.content_subtype = 'html' #if attachment1: # for a in attachment1: # msg.attach(a) msg.send() return True
def sendHtmlEmail(to,subject,context,template,cc,bcc,from_email,template_group,attachments=None): email_instance = env('EMAIL_INSTANCE','DEV') email_delivery = env('EMAIL_DELIVERY', 'off') override_email = env('OVERRIDE_EMAIL', None) context['default_url'] = env('DEFAULT_HOST', '') context['default_url_internal'] = env('DEFAULT_URL_INTERNAL', '') log_hash = int(hashlib.sha1(str(datetime.datetime.now()).encode('utf-8')).hexdigest(), 16) % (10 ** 8) email_log(str(log_hash)+' '+subject+":"+str(to)+":"+template_group) if email_delivery != 'on': print ("EMAIL DELIVERY IS OFF NO EMAIL SENT -- email.py ") return False if template is None: raise ValidationError('Invalid Template') if to is None: raise ValidationError('Invalid Email') if subject is None: raise ValidationError('Invalid Subject') if from_email is None: if settings.DEFAULT_FROM_EMAIL: from_email = settings.DEFAULT_FROM_EMAIL else: from_email = '*****@*****.**' django_version = int(str(django.VERSION[0])+''+str(django.VERSION[1])) pcontext = None if django_version > 110: pcontext = context else: pcontext = Context(context) context['version'] = settings.VERSION_NO # Custom Email Body Template context['body'] = get_template(template).render(pcontext) # Main Email Template Style ( body template is populated in the center if template_group == 'system-oim': main_template = get_template('email/base_email-oim.html').render(pcontext) reply_to=None if attachments is None: attachments = [] # Convert Documents to (filename, content, mime) attachment _attachments = [] for attachment in attachments: if isinstance(attachment, Document): filename = str(attachment) content = attachment.file.read() mime = mimetypes.guess_type(attachment.filename)[0] _attachments.append((filename, content, mime)) else: _attachments.append(attachment) if override_email is not None: to = override_email.split(",") if cc: cc = override_email.split(",") if bcc: bcc = override_email.split(",") if len(to) > 1: msg = EmailMultiAlternatives(subject, "Please open with a compatible html email client.", from_email=from_email, to=to, attachments=_attachments, cc=cc, bcc=bcc, reply_to=reply_to, headers={'System-Environment': email_instance}) msg.attach_alternative(main_template, 'text/html') #msg = EmailMessage(subject, main_template, to=[to_email],cc=cc, from_email=from_email) #msg.content_subtype = 'html' #if attachment1: # for a in attachment1: # msg.attach(a) try: email_log(str(log_hash)+' '+subject) msg.send() email_log(str(log_hash)+' Successfully sent to mail gateway') except Exception as e: email_log(str(log_hash)+' Error Sending - '+str(e)) else: msg = EmailMultiAlternatives(subject, "Please open with a compatible html email client.", from_email=from_email, to=to, attachments=_attachments, cc=cc, bcc=bcc, reply_to=reply_to, headers={'System-Environment': email_instance}) msg.attach_alternative(main_template, 'text/html') #msg = EmailMessage(subject, main_template, to=to,cc=cc, from_email=from_email) #msg.content_subtype = 'html' #if attachment1: # for a in attachment1: # msg.attach(a) try: email_log(str(log_hash)+' '+subject) msg.send() email_log(str(log_hash)+' Successfully sent to mail gateway') except Exception as e: email_log(str(log_hash)+' Error Sending - '+str(e)) return True
import os from confy import env, database, cache # Build paths inside the project like this: os.path.join(BASE_DIR, ...) PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__)) # Define the following in the environment: SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG', False) ALLOWED_HOSTS = [env("ALLOWED_DOMAIN"), ] # Base URL to use when referring to full URLs within the Wagtail admin backend - # e.g. in notification emails. Don't include '/admin' or a trailing slash BASE_URL = env('BASE_URL', 'http://localhost:8000') # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'compressor', 'taggit', 'modelcluster', 'django_extensions', 'reversion',
from django.core.exceptions import ImproperlyConfigured from confy import env, database import sys import dj_database_url import os # Project paths # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = None BASE_DIR_ENV = env('BASE_DIR', None) if BASE_DIR_ENV is None: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) else: BASE_DIR = BASE_DIR_ENV PROJECT_DIR = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'ledger') PAYMENT_OFFICERS_GROUP = env('PAYMENT_OFFICERS_GROUP', 'Payments Officers') LEDGER_API_KEY = env('LEDGER_API_KEY', "NO_KEY_PROVIDED") LEDGERGW_URL = env('LEDGERGW_URL', 'http://localhost/') LEDGER_API_URL = env('LEDGER_API_URL', 'http://localhost/') LEDGER_UI_URL = env('LEDGER_UI_URL', 'http://localhost/') # Application definitions SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG', False) CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if DEBUG: ALLOWED_HOSTS = ['*']
Django settings for the DPaW IBMS application. ''' from confy import database, env import os import sys from unipath import Path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).ancestor(2) PROJECT_DIR = os.path.join(BASE_DIR, 'ibms_project') # Add PROJECT_DIR to the system path. sys.path.insert(0, PROJECT_DIR) # Settings defined in environment variables. DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY') CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) INTERNAL_IPS = ['127.0.0.1', '::1'] if not DEBUG: # Localhost, UAT and Production hosts ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'ibms.dpaw.wa.gov.au', 'ibms.dpaw.wa.gov.au.', 'ibms-uat.dpaw.wa.gov.au', 'ibms-uat.dpaw.wa.gov.au.', ]
For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ from confy import env, database, cache import os # 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/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env('DEV') ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',
- Add Django Debug Toolbar - Add django-extensions as app """ import os import socket from confy import env from .common import * # noqa # Mail settings # ------------------------------------------------------------------------------ EMAIL_PORT = 1025 EMAIL_HOST = 'localhost' EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.console.EmailBackend') # CACHING # ------------------------------------------------------------------------------ # CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', # 'LOCATION': '' # } # } INTERNAL_IPS = ['127.0.0.1', '10.0.2.2', ] # tricks to have debug toolbar when developing with docker if os.environ.get('USE_DOCKER') == 'yes':
import os import sys from confy import env, database from unipath import Path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).ancestor(2) PROJECT_DIR = os.path.join(BASE_DIR, 'biosys') # Add PROJECT_DIR to the system path. sys.path.insert(0, PROJECT_DIR) # Add PROJECT_DIR/apps to the system path. sys.path.insert(0, os.path.join(PROJECT_DIR, 'apps')) # Security settings DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY', 'wjdh^hIO)jj5') CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if not DEBUG: ALLOWED_HOSTS = env('ALLOWED_DOMAINS', 'localhost').split(',') else: ALLOWED_HOSTS = ['*'] # Application definition # The variables below are added to all responses in biosys/context_processors.py SITE_TITLE = 'BioSys - WA Biological Survey Database' APPLICATION_VERSION_NO = '5.0.0' INSTALLED_APPS = ( 'grappelli', # Must be before django.contrib.admin
""" Django settings for resource_tracking project. """ from confy import env, database import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Application definition DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY') CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if not DEBUG: # Localhost, UAT and Production hosts: ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'sss.dpaw.wa.gov.au', 'sss.dpaw.wa.gov.au.', 'sss-uat.dpaw.wa.gov.au', 'sss-uat.dpaw.wa.gov.au.', ] INTERNAL_IPS = ['127.0.0.1', '::1'] ROOT_URLCONF = 'resource_tracking.urls' WSGI_APPLICATION = 'resource_tracking.wsgi.application' CSW_URL = env('CSW_URL', '') PRINTING_URL = env('PRINTING_URL', '') TRACPLUS_URL = env('TRACPLUS_URL', False)
def sendHtmlEmail(to, subject, context, template, cc, bcc, from_email, template_group, attachments=None): email_delivery = env('EMAIL_DELIVERY', 'off') override_email = env('OVERRIDE_EMAIL', None) context['default_url'] = env('DEFAULT_HOST', '') context['default_url_internal'] = env('DEFAULT_URL_INTERNAL', '') if email_delivery != 'on': print("EMAIL DELIVERY IS OFF NO EMAIL SENT -- email.py ") return False if template is None: raise ValidationError('Invalid Template') if to is None: raise ValidationError('Invalid Email') if subject is None: raise ValidationError('Invalid Subject') if from_email is None: if settings.DEFAULT_FROM_EMAIL: from_email = settings.DEFAULT_FROM_EMAIL else: from_email = '*****@*****.**' context['version'] = settings.VERSION_NO # Custom Email Body Template context['body'] = get_template(template).render(Context(context)) # Main Email Template Style ( body template is populated in the center if template_group == 'rottnest': main_template = get_template( 'mooring/email/base_email-rottnest.html').render(Context(context)) else: main_template = get_template('mooring/email/base_email2.html').render( Context(context)) reply_to = None if attachments is None: attachments = [] # Convert Documents to (filename, content, mime) attachment _attachments = [] for attachment in attachments: if isinstance(attachment, Document): filename = str(attachment) content = attachment.file.read() mime = mimetypes.guess_type(attachment.filename)[0] _attachments.append((filename, content, mime)) else: _attachments.append(attachment) if override_email is not None: to = override_email.split(",") if cc: cc = override_email.split(",") if bcc: bcc = override_email.split(",") if len(to) > 1: for to_email in to: msg = EmailMultiAlternatives( subject, "Please open with a compatible html email client.", from_email=from_email, to=to_email, attachments=_attachments, cc=cc, bcc=bcc, reply_to=reply_to) msg.attach_alternative(main_template, 'text/html') #msg = EmailMessage(subject, main_template, to=[to_email],cc=cc, from_email=from_email) #msg.content_subtype = 'html' #if attachment1: # for a in attachment1: # msg.attach(a) msg.send() else: msg = EmailMultiAlternatives( subject, "Please open with a compatible html email client.", from_email=from_email, to=to, attachments=_attachments, cc=cc, bcc=bcc, reply_to=reply_to) msg.attach_alternative(main_template, 'text/html') #msg = EmailMessage(subject, main_template, to=to,cc=cc, from_email=from_email) #msg.content_subtype = 'html' #if attachment1: # for a in attachment1: # msg.attach(a) msg.send() return True
> python manage.py runserver --settings=prs2.settings_dev.py """ from confy import env, database import os import sys from unipath import Path # Project paths # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).ancestor(2) PROJECT_DIR = os.path.join(BASE_DIR, 'prs2') # Add PROJECT_DIR to the system path. sys.path.insert(0, PROJECT_DIR) # Application definition DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY') CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if not DEBUG: # Localhost, UAT and Production hosts: ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'prs.dpaw.wa.gov.au', 'prs.dpaw.wa.gov.au.', 'prs-uat.dpaw.wa.gov.au', 'prs-uat.dpaw.wa.gov.au.', ] INTERNAL_IPS = ['127.0.0.1', '::1'] ROOT_URLCONF = 'prs2.urls'
import os from confy import env, database, cache from dj_database_url import parse # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Define the following in the environment: SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG', False) if not DEBUG: ALLOWED_HOSTS = env('ALLOWED_DOMAINS', '').split(',') else: ALLOWED_HOSTS = ['*'] INTERNAL_IPS = ['127.0.0.1', '::1'] # Base URL to use when referring to full URLs within the Wagtail admin backend # e.g. in notification emails. Don't include '/admin' or a trailing slash BASE_URL = env('BASE_URL', 'http://localhost:8000') BORG_URL = env('BORG_URL', 'https://borg.dpaw.wa.gov.au') if BORG_URL.endswith('/'): BORG_URL = BORG_URL[:-1] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',
""" # Build paths inside the project like this: os.path.join(BASE_DIR, ...) from confy import env, database import os import sys # Project paths # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.join(BASE_DIR, 'caddy') # Add PROJECT_DIR to the system path. sys.path.insert(0, PROJECT_DIR) # Application definition DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY', 'PlaceholderSecretKey') CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if not DEBUG: ALLOWED_HOSTS = env('ALLOWED_DOMAINS', '').split(',') else: ALLOWED_HOSTS = ['*'] INTERNAL_IPS = ['127.0.0.1', '::1'] ROOT_URLCONF = 'caddy.urls' WSGI_APPLICATION = 'caddy.wsgi.application' INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',
import os from confy import env, database, cache # Build paths inside the project like this: os.path.join(BASE_DIR, ...) PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__)) # Define the following in the environment: SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG', False) ALLOWED_HOSTS = [env("ALLOWED_DOMAIN"), ] # Base URL to use when referring to full URLs within the Wagtail admin backend - # e.g. in notification emails. Don't include '/admin' or a trailing slash BASE_URL = env('BASE_URL', 'http://localhost:8000') BORG_URL = env("BORG_URL","https://borg.dpaw.wa.gov.au") if BORG_URL.endswith("/"): BORG_URL = BORG_URL[:-1] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'compressor',
from confy import read_environment_file, env import os from fabric.api import cd, run, local, get, settings from fabric.contrib.files import exists, upload_template read_environment_file() DEPLOY_REPO_URL = env("DEPLOY_REPO_URL", "") DEPLOY_TARGET = env("DEPLOY_TARGET", "") DEPLOY_VENV_PATH = env("DEPLOY_VENV_PATH", "") DEPLOY_VENV_NAME = env("DEPLOY_VENV_NAME", "") DEPLOY_DEBUG = env("DEPLOY_DEBUG", "") DEPLOY_DATABASE_URL = env("DEPLOY_DATABASE_URL", "") DEPLOY_SECRET_KEY = env("DEPLOY_SECRET_KEY", "") DEPLOY_CSRF_COOKIE_SECURE = env("DEPLOY_CSRF_COOKIE_SECURE", "") DEPLOY_SESSION_COOKIE_SECURE = env("DEPLOY_SESSION_COOKIE_SECURE", "") DEPLOY_USER = env("DEPLOY_USER", "") DEPLOY_DB_NAME = env("DEPLOY_DB_NAME", "db") DEPLOY_DB_USER = env("DEPLOY_DB_USER", "dbuser") DEPLOY_SUPERUSER_USERNAME = env("DEPLOY_SUPERUSER_USERNAME", "superuser") DEPLOY_SUPERUSER_EMAIL = env("DEPLOY_SUPERUSER_EMAIL", "*****@*****.**") DEPLOY_SUPERUSER_PASSWORD = env("DEPLOY_SUPERUSER_PASSWORD", "pass") DEPLOY_SUPERVISOR_NAME = env("DEPLOY_SUPERVISOR_NAME", "sv") DEPLOY_EMAIL_HOST = env("DEPLOY_EMAIL_HOST", "email.host") DEPLOY_EMAIL_PORT = env("DEPLOY_EMAIL_PORT", "25") DEPLOY_SITE_URL = env("SITE_URL", "url") GEOSERVER_WMS_URL = env("GEOSERVER_WMS_URL", "url") GEOSERVER_WFS_URL = env("GEOSERVER_WFS_URL", "url") BORGCOLLECTOR_API = env("BORGCOLLECTOR_API", "url") SSO_COOKIE_NAME = env("SSO_COOKIE_NAME", "oim_dpaw_wa_gov_au_sessionid") PRS_USER_GROUP = env("PRS_USER_GROUP", "PRS user") PRS_PWUSER_GROUP = env("PRS_PWUSER_GROUP", "PRS power user")
from confy import env, database import os # Project paths # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Application definition DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY') S3_FOLDER = env('S3_FOLDER') CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if not DEBUG: # Localhost, UAT and Production hosts ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'kens-xenmate-dev', 'penguins.dpaw.wa.gov.au', 'penguins.dpaw.wa.gov.au.', 'penguins-test.dpaw.wa.gov.au', 'penguins-test.dpaw.wa.gov.au.', ] INTERNAL_IPS = ['127.0.0.1', '::1'] ROOT_URLCONF = 'penguins.urls' WSGI_APPLICATION = 'penguins.wsgi.application' INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.contenttypes',
from confy import env, database import os # Project paths # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.join(BASE_DIR, 'ledger') # Application definitions SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG', False) CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if not DEBUG: ALLOWED_HOSTS = [] # FIXME in production ROOT_URLCONF = 'ledger.urls' ROOT_HOSTCONF = 'ledger.hosts' DEFAULT_HOST = env('DEFAULT_HOST', 'ledger') PARENT_HOST = env('PARENT_HOST', 'localhost') HOST_PORT = env('HOST_PORT', '8000') WSGI_APPLICATION = 'ledger.wsgi.application' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'social.apps.django_app.default', 'django_extensions',
from confy import env, database import os import sys from unipath import Path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).ancestor(2) PROJECT_DIR = os.path.join(BASE_DIR, 'biosys') # Add PROJECT_DIR to the system path. sys.path.insert(0, PROJECT_DIR) # Add PROJECT_DIR/apps to the system path. sys.path.insert(0, os.path.join(PROJECT_DIR, 'apps')) # Security settings DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY') CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if not DEBUG: # Localhost, UAT and Production hosts ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'biosys.dpaw.wa.gov.au', 'biosys.dpaw.wa.gov.au.', 'biosys-uat.dpaw.wa.gov.au', 'biosys-uat.dpaw.wa.gov.au.', ] # Application definition
from confy import env, database from oscar.defaults import * from oscar import get_core_apps, OSCAR_MAIN_TEMPLATE_DIR import os # Project paths # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.join(BASE_DIR, 'ledger') # Application definitions SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG', False) CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) if not DEBUG: ALLOWED_HOSTS = env('ALLOWED_HOSTS', []) ROOT_URLCONF = 'ledger.urls' ROOT_HOSTCONF = 'ledger.hosts' DEFAULT_HOST = env('DEFAULT_HOST', 'ledger') PARENT_HOST = env('PARENT_HOST', 'localhost') HOST_PORT = env('HOST_PORT', '8000') WSGI_APPLICATION = 'ledger.wsgi.application' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages',
from django.core.exceptions import ImproperlyConfigured import os from confy import env import confy BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) confy.read_environment_file(BASE_DIR + "/.env") os.environ.setdefault("BASE_DIR", BASE_DIR) from ledger.settings_base import * ROOT_URLCONF = 'mooringlicensing.urls' SITE_ID = 1 DEPT_DOMAINS = env('DEPT_DOMAINS', ['dpaw.wa.gov.au', 'dbca.wa.gov.au']) SYSTEM_MAINTENANCE_WARNING = env('SYSTEM_MAINTENANCE_WARNING', 24) # hours DISABLE_EMAIL = env('DISABLE_EMAIL', False) SHOW_TESTS_URL = env('SHOW_TESTS_URL', False) SHOW_DEBUG_TOOLBAR = env('SHOW_DEBUG_TOOLBAR', False) if SHOW_DEBUG_TOOLBAR: def show_toolbar(request): return True MIDDLEWARE_CLASSES += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INSTALLED_APPS += ('debug_toolbar', ) INTERNAL_IPS = ('127.0.0.1', 'localhost') # this dict removes check to dtermine if toolbar should display --> works for rks docker container
import sys from platform import system from confy import env, database from unipath import Path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).ancestor(2) PROJECT_DIR = os.path.join(BASE_DIR, 'biosys') # Add PROJECT_DIR to the system path. sys.path.insert(0, PROJECT_DIR) # Add PROJECT_DIR/apps to the system path. sys.path.insert(0, os.path.join(PROJECT_DIR, 'apps')) # Security settings DEBUG = env('DEBUG', False) SECRET_KEY = env('SECRET_KEY', 'wjdh^hIO)jj5') CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False) SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False) ALLOWED_HOSTS = env('ALLOWED_HOSTS', [ 'localhost', '127.0.0.1', 'biosys.dbca.wa.gov.au', 'biosys.dbca.wa.gov.au.', 'biosys-uat.dbca.wa.gov.au', 'biosys-uat.dbca.wa.gov.au.', ]) if system() == 'Windows': GDAL_LIBRARY_PATH = env('GDAL_LIBRARY_PATH') GEOS_LIBRARY_PATH = env('GEOS_LIBRARY_PATH')
import os from confy import env, database, cache # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Define the following in the environment: SECRET_KEY = env("SECRET_KEY") DEBUG = env("DEBUG", False) ALLOWED_HOSTS = [env("ALLOWED_DOMAIN")] INTERNAL_IPS = ["127.0.0.1", "::1"] # Base URL to use when referring to full URLs within the Wagtail admin backend # e.g. in notification emails. Don't include '/admin' or a trailing slash BASE_URL = env("BASE_URL", "http://localhost:8000") BORG_URL = env("BORG_URL", "https://borg.dpaw.wa.gov.au") if BORG_URL.endswith("/"): BORG_URL = BORG_URL[:-1] # Application definition INSTALLED_APPS = ( "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.humanize", "compressor", "taggit", "modelcluster",
import os from confy import env, database, cache # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Define the following in the environment: SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG', False) ALLOWED_HOSTS = [env('ALLOWED_DOMAIN'), ] INTERNAL_IPS = ['127.0.0.1', '::1'] # Base URL to use when referring to full URLs within the Wagtail admin backend # e.g. in notification emails. Don't include '/admin' or a trailing slash BASE_URL = env('BASE_URL', 'http://localhost:8000') BORG_URL = env('BORG_URL', 'https://borg.dpaw.wa.gov.au') if BORG_URL.endswith('/'): BORG_URL = BORG_URL[:-1] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'compressor', 'taggit',
from confy import database, env import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration from unipath import Path # import confy # confy.read_environment_file() ROOT_DIR = environ.Path(__file__) - 3 # (wastd/config/settings/common.py - 3 = wastd/) BASE_DIR = Path(__file__).ancestor(3) APPS_DIR = ROOT_DIR.path('wastd') # DEBUG # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = env('DJANGO_DEBUG', default=False) PROFILING = env('DJANGO_PROFILING', default=False) ANIMALS_PK = env("ANIMALS_PK", default=20) PLANTS_PK = env("PLANTS_PK", default=21) # APP CONFIGURATION # ------------------------------------------------------------------------------ DJANGO_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages',
def import_harvested_refs(): """Process harvested referrals and generate referrals & records within PRS """ actions = [] logger.info('Starting import of harvested referrals') actions.append('{} Starting import of harvested referrals'.format(datetime.now().isoformat())) dpaw = Agency.objects.get(slug='dpaw') wapc = Organisation.objects.get(slug='wapc') assess_task = TaskType.objects.get(name='Assess a referral') assignee_default = User.objects.get(username=settings.REFERRAL_ASSIGNEE_FALLBACK) # Process harvested refs that are unprocessed at present. for er in EmailedReferral.objects.filter(referral__isnull=True, processed=False): attachments = er.emailattachment_set.all() # Emails without attachments are usually reminder notices. if not attachments.exists(): logger.info('Skipping harvested referral {} (no attachments)'.format(er)) actions.append('{} Skipping harvested referral {} (no attachments)'.format(datetime.now().isoformat(), er)) er.processed = True er.save() continue # Must be an attachment named 'Application.xml' present to import. if not attachments.filter(name__istartswith='application.xml'): logger.info('Skipping harvested referral {} (no XML attachment)'.format(er)) actions.append('{} Skipping harvested referral {} (no XML attachment)'.format(datetime.now().isoformat(), er)) er.processed = True er.save() continue else: xml_file = attachments.get(name__istartswith='application.xml') try: d = xmltodict.parse(xml_file.attachment.read()) except Exception as e: logger.error('Harvested referral {} parsing of application.xml failed'.format(er)) logger.exception(e) actions.append('{} Harvested referral {} parsing of application.xml failed'.format(datetime.now().isoformat(), er)) er.processed = True er.save() continue app = d['APPLICATION'] ref = app['WAPC_APPLICATION_NO'] if Referral.objects.current().filter(reference__icontains=ref): # Note if the the reference no. exists in PRS already. logger.info('Referral ref {} is already in database'.format(ref)) actions.append('{} Referral ref {} is already in database'.format(datetime.now().isoformat(), ref)) referral_preexists = True new_ref = Referral.objects.current().filter(reference__icontains=ref).order_by('-pk').first() else: referral_preexists = False if not referral_preexists: # No match with existing references; import the harvested referral. logger.info('Importing harvested referral ref {}'.format(ref)) actions.append('{} Importing harvested referral ref {}'.format(datetime.now().isoformat(), ref)) try: ref_type = ReferralType.objects.filter(name__istartswith=app['APP_TYPE'])[0] except: logger.warning('Referral type {} is not recognised type; skipping'.format(app['APP_TYPE'])) actions.append('{} Referral type {} is not recognised type; skipping'.format(datetime.now().isoformat(), app['APP_TYPE'])) er.processed = True er.save() continue # Determine the intersecting region(s). regions = [] assigned = None # ADDRESS_DETAIL may or may not be a list :/ if not isinstance(app['ADDRESS_DETAIL']['DOP_ADDRESS_TYPE'], list): addresses = [app['ADDRESS_DETAIL']['DOP_ADDRESS_TYPE']] else: addresses = app['ADDRESS_DETAIL']['DOP_ADDRESS_TYPE'] # Address geometry: url = env('SLIP_WFS_URL', None) auth = (env('SLIP_USERNAME', None), env('SLIP_PASSWORD', None)) type_name = env('SLIP_DATASET', '') locations = [] for a in addresses: # Use the long/lat info to intersect DPaW regions. try: p = Point(x=float(a['LONGITUDE']), y=float(a['LATITUDE'])) for r in Region.objects.all(): if r.region_mpoly and r.region_mpoly.intersects(p) and r not in regions: regions.append(r) except: logger.warning('Address long/lat could not be parsed ({}, {})'.format(a['LONGITUDE'], a['LATITUDE'])) actions.append('{} Address long/lat could not be parsed ({}, {})'.format(datetime.now().isoformat(), a['LONGITUDE'], a['LATITUDE'])) # Use the PIN field to try returning geometry from SLIP. if 'PIN' in a: pin = int(a['PIN']) if pin > 0: params = { 'service': 'WFS', 'version': '1.0.0', 'typeName': type_name, 'request': 'getFeature', 'outputFormat': 'json', 'cql_filter': 'polygon_number={}'.format(pin) } try: resp = requests.get(url, auth=auth, params=params) if resp.json()['features']: # Features are Multipolygons. a['FEATURES'] = resp.json()['features'] # List of MP features. locations.append(a) # A dict for each address location. logger.info('Address PIN {} returned geometry from SLIP'.format(pin)) except: logger.error('Error querying Landgate SLIP for spatial data (referral ref {})'.format(ref)) else: logger.warning('Address PIN could not be parsed ({})'.format(a['PIN'])) # Business rules: # Didn't intersect a region? Might be bad geometry in the XML. # Likewise if >1 region was intersected, default to Swan Region # and the designated fallback user. if len(regions) == 0: region = Region.objects.get(name='Swan') assigned = assignee_default logger.warning('No regions were intersected, defaulting to {} ({})'.format(region, assigned)) elif len(regions) > 1: region = Region.objects.get(name='Swan') assigned = assignee_default logger.warning('>1 regions were intersected ({}), defaulting to {} ({})'.format(regions, region, assigned)) else: region = regions[0] try: assigned = RegionAssignee.objects.get(region=region).user except: logger.warning('No default assignee set for {}, defaulting to {}'.format(region, assignee_default)) actions.append('{} No default assignee set for {}, defaulting to {}'.format(datetime.now().isoformat(), region, assignee_default)) assigned = assignee_default # Create the referral in PRS. new_ref = Referral.objects.create( type=ref_type, agency=dpaw, referring_org=wapc, reference=ref, description=app['DEVELOPMENT_DESCRIPTION'], referral_date=er.received, address=app['LOCATION']) logger.info('New PRS referral generated: {}'.format(new_ref)) actions.append('{} New PRS referral generated: {}'.format(datetime.now().isoformat(), new_ref)) # Assign to a region. new_ref.region.add(region) # Assign an LGA. try: new_ref.lga = LocalGovernment.objects.get(name=app['LOCAL_GOVERNMENT']) new_ref.save() except: logger.warning('LGA {} was not recognised'.format(app['LOCAL_GOVERNMENT'])) actions.append('{} LGA {} was not recognised'.format(datetime.now().isoformat(), app['LOCAL_GOVERNMENT'])) # Add triggers to the new referral. triggers = [i.strip() for i in app['MRSZONE_TEXT'].split(',')] added_trigger = False for i in triggers: if DopTrigger.objects.current().filter(name__istartswith=i).exists(): added_trigger = True new_ref.dop_triggers.add(DopTrigger.objects.current().get(name__istartswith=i)) elif i.startswith('BUSH FOREVER SITE'): added_trigger = True new_ref.dop_triggers.add(DopTrigger.objects.get(name='Bush Forever site')) # If we didn't link any DoP triggers, link the "No Parks and Wildlife trigger" tag. if not added_trigger: new_ref.dop_triggers.add(DopTrigger.objects.get(name='No Parks and Wildlife trigger')) # Add locations to the new referral (one per polygon in each MP geometry). new_locations = [] for l in locations: for f in l['FEATURES']: geom = GEOSGeometry(json.dumps(f['geometry'])) for p in geom: new_loc = Location.objects.create( address_no=int(a['NUMBER_FROM']) if a['NUMBER_FROM'] else None, address_suffix=a['NUMBER_FROM_SUFFIX'], road_name=a['STREET_NAME'], road_suffix=a['STREET_SUFFIX'], locality=a['SUBURB'], postcode=a['POSTCODE'], referral=new_ref, poly=p ) new_locations.append(new_loc) logger.info('New PRS location generated: {}'.format(new_loc)) actions.append('{} New PRS location generated: {}'.format(datetime.now().isoformat(), new_loc)) # Check to see if new locations intersect with any existing locations. intersecting = [] for l in new_locations: other_l = Location.objects.current().exclude(pk=l.pk).filter(poly__isnull=False, poly__intersects=l.poly) if other_l.exists(): intersecting += list(other_l) # For any intersecting locations, relate the new and existing referrals. for l in intersecting: if l.referral.pk != new_ref.pk: new_ref.add_relationship(l.referral) logger.info('New referral {} related to existing referral {}'.format(new_ref.pk, l.referral.pk)) actions.append('{} New referral {} related to existing referral {}'.format(datetime.now().isoformat(), new_ref.pk, l.referral.pk)) # Create an "Assess a referral" task and assign it to a user. new_task = Task( type=assess_task, referral=new_ref, start_date=new_ref.referral_date, description=new_ref.description, assigned_user=assigned ) new_task.state = assess_task.initial_state new_task.due_date = datetime.today() + timedelta(assess_task.target_days) new_task.save() logger.info('New PRS task generated: {} assigned to {}'.format(new_task, assigned.get_full_name())) actions.append('{} New PRS task generated: {} assigned to {}'.format(datetime.now().isoformat(), new_task, assigned.get_full_name())) # Email the assigned user about the new task. new_task.email_user() logger.info('Task assignment email sent to {}'.format(assigned.email)) actions.append('{} Task assignment email sent to {}'.format(datetime.now().isoformat(), assigned.email)) # Save the EmailedReferral as a record on the referral. new_record = Record.objects.create( name=er.subject, referral=new_ref, order_date=datetime.today()) file_name = 'emailed_referral_{}.html'.format(ref) new_file = File(StringIO(er.body)) new_record.uploaded_file.save(file_name, new_file) new_record.save() logger.info('New PRS record generated: {}'.format(new_record)) actions.append('{} New PRS record generated: {}'.format(datetime.now().isoformat(), new_record)) # Add records to the referral (one per attachment). for i in attachments: new_record = Record.objects.create( name=i.name, referral=new_ref, order_date=datetime.today()) # Duplicate the uploaded file. data = StringIO(i.attachment.read()) new_file = File(data) new_record.uploaded_file.save(i.name, new_file) new_record.save() logger.info('New PRS record generated: {}'.format(new_record)) actions.append('{} New PRS record generated: {}'.format(datetime.now().isoformat(), new_record)) # Link the attachment to the new, generated record. i.record = new_record i.save() # Link the emailed referral to the new or existing referral. er.referral = new_ref er.processed = True er.save() logger.info('Import process completed') actions.append('{} Import process completed'.format(datetime.now().isoformat())) return actions