Esempio n. 1
0
#!/usr/bin/env python
import confy
import os
import sys
import json
import string
import psycopg2

from confy import env, database, cache
from subprocess import call
from django.utils.encoding import smart_str
from types import NoneType

confy.read_environment_file()

locmap = {} 
suppliermap = {}
dupecache = {}

# New Database Connection
newdbconn = psycopg2.connect(database=env("NEW_DB"), user=env("NEW_DB_USER"), password=env("NEW_DB_PASS"), host=env("NEW_DB_HOST"), port="5432")
# OLD database Connection 
olddbconn = psycopg2.connect(database=env("OLD_DB"), user=env("OLD_DB_USER"), password=env("OLD_DB_PASS"), host=env("OLD_DB_HOST"), port="5432")

newcur = newdbconn.cursor()
oldcur = olddbconn.cursor()

# Assets_Supplier
tablemap = {}
rowjson = {}
tablemap['id'] = 0
Esempio n. 2
0
from django.core.exceptions import ImproperlyConfigured

import os, hashlib
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 = 'commercialoperator.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)
BUILD_TAG = env(
    'BUILD_TAG',
    hashlib.md5(os.urandom(
        32)).hexdigest())  # URL of the Dev app.js served by webpack & express

if SHOW_DEBUG_TOOLBAR:
    #    def get_ip():
    #        import subprocess
    #        route = subprocess.Popen(('ip', 'route'), stdout=subprocess.PIPE)
    #        network = subprocess.check_output(
    #            ('grep', '-Po', 'src \K[\d.]+\.'), stdin=route.stdout
    #        ).decode().rstrip()
    #        route.wait()
    #        network_gateway = network + '1'
Esempio n. 3
0
import os
import sys
import confy
from django.core.wsgi import get_wsgi_application
try:
    confy.read_environment_file('.env')
except:
    print('ERROR: Script must be runs from PROJECT BASE_DIR')
    exit()

application = get_wsgi_application() # This is so models get loaded.

proj_path = os.getcwd()
sys.path.append(proj_path)
os.chdir(proj_path)

# ----------------------------------------------------------------------------------------
# Script starts here
# ----------------------------------------------------------------------------------------

import csv
from datetime import datetime, date
import pytz
from pbs.prescription.models import Prescription

def read_ids(filename):
    return [i[0].strip() for i in list(csv.reader(open(filename), delimiter=',', quotechar='"'))]

def remove_approvals(ids):
    # Copied in from remove_approvals.py then updated
    # Used to remove corporate approval from ePFPs
Esempio n. 4
0
from __future__ import absolute_import

import confy
confy.read_environment_file(".env")

import django
django.setup()

from django.conf import settings
from django.http import HttpResponse
from django.utils import timezone
from django.utils.encoding import force_text
from django.template.defaultfilters import date
from uwsgidecorators import timer, harakiri
import csv
import os
import paramiko
import StringIO
import sys
import telnetlib
from datetime import timedelta
import logging

logger = logging.getLogger('log')

from weather.models import WeatherStation, WeatherObservation


def ftp_upload(host, port, username, password, observations):
    logger.debug("Connecting to %s..." % host)
Esempio n. 5
0
import os
import sys
import confy
from django.core.wsgi import get_wsgi_application
try:
    confy.read_environment_file('.env')
except:
    print('ERROR: Script must be runs from PROJECT BASE_DIR')
    exit()

application = get_wsgi_application() # This is so models get loaded.

proj_path = os.getcwd()
sys.path.append(proj_path)
os.chdir(proj_path)

# ----------------------------------------------------------------------------------------
# Script starts here
# ----------------------------------------------------------------------------------------

from pbs.prescription.models import Prescription

def update():
    for p in Prescription.objects.all():
        p.description = p.generate_description()
        p.save()


if __name__ == "__main__":
    update()
Esempio n. 6
0
import confy
import django
from confy import database

# -- Django configuration -------------------------------------------------
# 1. Add Django ROOT_DIR to sys.path, so conf.py can discover django settings
sys.path.insert(0, os.path.abspath('..'))
# print("The Sphinx conf.py now also discovers python modules "
#       "relative to the Django root dir {0}".format(sys.path[0]))

# 2. Set env var pointing to our Django settings module, so django.setup() knows
# which settings to use
# IMPORTANT: use SINGLE quotes for the settings module
os.environ['DJANGO_SETTINGS_MODULE'] = 'config.settings.local'
try:
    confy.read_environment_file(".env")
except:
    pass

DATABASES = {'default': database.config()}
DATABASES['default']['ATOMIC_REQUESTS'] = True


# 3. Setup the Django app, so that autodoc will find the modules this help references
try:
    django.setup()
except:
    raise
# print("Now the Django settings are loaded, e.g. installed apps are:"
#       "{0}".format(", ".join([app for app in settings.INSTALLED_APPS])))
Esempio n. 7
0
#!/usr/bin/env python
import os
import sys
import confy

confy.read_environment_file(envfile=".env")

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)
Esempio n. 8
0
"""
WSGI config for ledger project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
import os
from django.core.wsgi import get_wsgi_application

import confy
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
confy.read_environment_file(BASE_DIR+"/.env")

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mooring.settings")
application = get_wsgi_application()
Esempio n. 9
0
"""
WSGI config for IBMS project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
import confy
from django.core.wsgi import get_wsgi_application
import os
from pathlib import Path

# These lines are required for interoperability between local and container environments.
d = Path(__file__).resolve().parents[1]
dot_env = os.path.join(str(d), '.env')
if os.path.exists(dot_env):
    confy.read_environment_file(dot_env)

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ibms_project.settings')
application = get_wsgi_application()
Esempio n. 10
0
"""
WSGI config for parkourdex 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/2.1/howto/deployment/wsgi/
"""
import confy
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
dot_env = os.path.join(BASE_DIR, '.env')
if os.path.exists(dot_env):
    confy.read_environment_file(dot_env)  # Must precede dj_static imports.

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'parkourdex.settings')

application = get_wsgi_application()
Esempio n. 11
0
#!/usr/bin/env python
import confy
import os
import sys

# These lines are required for interoperability between local and container environments.
dot_env = os.path.join(os.getcwd(), '.env')
if os.path.exists(dot_env):
    confy.read_environment_file(confy.env('ENV_FILE'))

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "biosys.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django
        except ImportError:
            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?")
        raise
    execute_from_command_line(sys.argv)
Esempio n. 12
0
"""
WSGI config for ledger/parkstay project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
import confy
from django.core.wsgi import get_wsgi_application
import os

dot_env = os.path.join(os.getcwd(), '.env')
if os.path.exists(dot_env):
    confy.read_environment_file(
        ".env")  # This line must precede dj_static imports.

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "parkstay.settings")
from dj_static import Cling, MediaCling
application = Cling(MediaCling(get_wsgi_application()))
Esempio n. 13
0
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")
Esempio n. 14
0
#!/usr/bin/env python
import confy
import sys

confy.read_environment_file()

if __name__ == "__main__":
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)
Esempio n. 15
0
"""
WSGI config for scrooge project.

It exposes the WSGI callable as a module-level variable named ``application``.
"""
import os
import confy
from pathlib import Path

# These lines are required for interoperability between local and container environments.
d = Path(__file__).resolve().parents[1]
dot_env = os.path.join(str(d), '.env')
if os.path.exists(dot_env):
    confy.read_environment_file(dot_env)

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "scrooge.settings")

application = get_wsgi_application()
Esempio n. 16
0
"""
WSGI config for resource_tracking project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
import confy
confy.read_environment_file('.env')  # Must precede dj_static imports.
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "resource_tracking.settings")
application = Cling(get_wsgi_application())
Esempio n. 17
0
    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()