[ create a new paste ] login | about

Link: http://codepad.org/Dp1ZiViV    [ raw code | output | fork ]

Python, pasted on May 26:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
__author__ = 'Administrator'
#JSON Web-Service to Enterprise Geodatabase
#By Geoffrey West
#SANSTAR/SOS City of Los Angeles BOS

import json
import jsonpickle
import requests
import arcpy
import numpy as np
import datetime
from email.mime.text import MIMEText
import sys
import traceback
import smtplib
from email.MIMEText import MIMEText
import time
import datetime
import logging
import logging.handlers
import io


arcpy.env.workspace = ""



class TlsSMTPHandler(logging.handlers.SMTPHandler):
    def emit(self, record):
        """
        Emit a record.

        Format the record and send it to the specified addressees.
        """
        try:
            import smtplib
            import string # for tls add this line
            try:
                from email.utils import formatdate
            except ImportError:
                formatdate = self.date_time
            port = self.mailport
            if not port:
                port = smtplib.SMTP_PORT
            smtp = smtplib.SMTP(self.mailhost, port)
            msg = self.format(record)
            msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
                            self.fromaddr,
                            string.join(self.toaddrs, ","),
                            self.getSubject(record),
                            formatdate(), msg)
            if self.username:
                smtp.ehlo() # for tls add this line
                smtp.starttls() # for tls add this line
                smtp.ehlo() # for tls add this line
                smtp.login(self.username, self.password)
            smtp.sendmail(self.fromaddr, self.toaddrs, msg)
            smtp.quit()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

logger = logging.getLogger()

gm = TlsSMTPHandler(("smtp.gmail.com", 587), 'geoffreywestgis@gmail.com', ['geoffreywestgis@gmail.com'], 'Error found!', ('geoffreywestgis@gmail.com', 'password'))
gm.setLevel(logging.ERROR)

logger.addHandler(gm)

try:
    def sendResultEmail(msgContents, success_TF):
            '''sendResultEmail(msgContents, success_TF)
            This is the module that does the sending - you should only need to edit the top four active lines'''
            to = 'geoffreywestgis@gmail.com'
            send_username = 'geoffreywestgis@gmail.com'
            send_password = 'password' # warning - will just be an unencrypted string - so be careful not to leave this file lying around!
            smtpserver = smtplib.SMTP("smtp.gmail.com",587)


            if success_TF:
                subject = 'Arcpy testing results: script SUCCESS.'
            else:
                subject = 'Arcpy testing results: script FAILURE.'

            smtpserver.ehlo()
            smtpserver.starttls()
            smtpserver.ehlo
            smtpserver.login(send_username, send_password)

            header = 'To:' + to + '\n' + 'From: ' + send_username + '\n' + 'Subject:' + subject + '\n'

            msg = header + '\nArcpy results: Listed Below! \n\t' + msgContents + '\n'

            smtpserver.sendmail(send_username, to, msg)

            arcpy.AddMessage('This is a good thing!!')

            smtpserver.close()

    success = True or False
    strResult = ''

    arcpy.SetLogHistory(True)
    start = time.time()
    Start = datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S')
    msgFolder = "C:/logs/"
    sender = "geoffreywestgis@gmail.com"
    recipient = "geoffreywestgis@gmail.com"
    fc2 = "C:\Users\Administrator\AppData\Roaming\ESRI\Desktop10.2\ArcCatalog\Connection to localhost_ServiceRequest.sde\ServiceRequest.DBO.MYLA311"
    fc = "C:\Users\Administrator\AppData\Roaming\ESRI\Desktop10.2\ArcCatalog\Connection to localhost_ServiceRequest.sde\ServiceRequest.DBO.MYLA311AppendFeature"
    aTable = "C:\Users\GeoffreyWest\AppData\Roaming\ESRI\Desktop10.2\ArcCatalog\ServiceRequest.sde\ServiceRequest.DBO.History_Table_"
    connect_timeout = 5
    f2 =open('C:\Users\GeoffreyWest\Desktop\Request.json')
    data2 = jsonpickle.decode((f2.read()))

    Start = datetime.datetime.now()
    DD = datetime.timedelta(minutes=5)
    earlier = Start - DD
    earlier_str = earlier.strftime('X%m/%d/%Y %H:%M:%S').replace('X0','X').replace('X','')
    #
    # for datatime in data2:
    #     DataTime = data2["SRData"]['LastUpdatedDate'] = str(earlier_str)
    data2 = jsonpickle.encode(data2)



    print data2
    url2 = "https://myla311.lacity.org/myla311router/mylasrbe/1/SANQuerySR"
    headers2 = {'Content-type': 'text/plain', 'Accept': '/'}

    r2 = requests.post(url2, data=data2, headers=headers2)
    decoded2 = json.loads(r2.text)
    print json.dumps(decoded2, sort_keys=True, indent=4)


    Start = datetime.datetime.now()
    i = 5
    i2= 10
    now_minus_5 = Start - datetime.timedelta(minutes =i)
    now_minus_10 = Start - datetime.timedelta(minutes =i2)



    try:
        if arcpy.Exists(fc):
            arcpy.Delete_management(fc)
        try:
            r2
        except requests.exceptions.ConnectTimeout as e:
            print "Too slow Mojo!"


        order_fld =  "Time"
        return_flds = ["Time", "SUCCESS"]
        where_str = """Time != DATEADD(minute, -10,  GETDATE()) AND SUCCESS = 'NO'"""
        sql_clause = (None,'ORDER BY {} DESC'.format(order_fld))
        last_row = ''
        with arcpy.da.SearchCursor(aTable, return_flds, where_clause=where_str, sql_clause=sql_clause) as cursor:
            last_row = cursor.next()
            last_time = last_row[0]
            last_success = last_row[1]
            last_run = datetime.datetime.strptime(last_time,"%m/%d/%Y %H:%M")
            print last_row
            print last_run
            print last_success


            try:
                if last_run != now_minus_5:
                    print "this block is activated"

                items = []
                for sr in decoded2['Response']['ListOfServiceRequest']['ServiceRequest']:
                    SRAddress = sr['SRAddress']
                    # SRType = sr['SRType']
                    if sr['Latitude'] != '':
                        y = sr['Latitude']
                    if sr['Longitude'] != '':
                        x = sr['Longitude']
                    if sr['Latitude'] == '':
                        blanky = sr['Latitude']
                    if sr['Longitude'] == '':
                        blankx= sr['Longitude']
                        print blanky
                        print blankx
                    ReasonCode = sr['ReasonCode']
                    SRNumber = sr['SRNumber']
                    FirstName = sr['FirstName']
                    LastName = sr['LastName']
                    ResolutionCode = sr['ResolutionCode']
                    HomePhone = sr['HomePhone']
                    CreatedDate = sr['CreatedDate']
                    UpdatedDate = sr['UpdatedDate']
                    BulkyItem = sr['ListOfLa311BulkyItem']
                    ElectronicWaste = sr['ListOfLa311ElectronicWaste']
                    MoveInMoveOut = sr['ListOfLa311MoveInMoveOut']
                    IllegalDumping = sr['ListOfLa311IllegalDumpingPickup']
                    ServiceNotComplete = sr['ListOfLa311ServiceNotComplete']
                    BrushItems = sr['ListOfLa311BrushItemsPickup']
                    Containers = sr['ListOfLa311Containers']
                    MHA = sr['ListOfLa311MetalHouseholdAppliancesPickup']
                    DeadAnimalRemoval = sr['ListOfLa311DeadAnimalRemoval']
                    Manual = sr['ListOfLa311ManualPickup']


                    CreatedDate = datetime.datetime.strptime(CreatedDate, "%m/%d/%Y %H:%M:%S")
                    UpdatedDate = datetime.datetime.strptime(UpdatedDate, "%m/%d/%Y %H:%M:%S")

                    BulkyItemInfo = " "
                    EwasteItemInfo = " "
                    MHAItemInfo = " "
                    DACItemInfo = " "
                    ServiceNotCompleteInfo = " "
                    ManualPickUpInfo= " "
                    BrushItemInfo = " "
                    MoveInMoveOutInfo  =  " "
                    ContainersInfo =  " "
                    IllegalDumpingInfo = " "



                    try:
                        locationEwastePrevious = ''
                        for sr in ElectronicWaste:
                                for ewastelocation in ElectronicWaste['La311ElectronicWaste']:
                                                    locationewaste = ewastelocation['CollectionLocation']
                                                    if locationEwastePrevious != locationewaste:
                                                        locationEwastePrevious = locationewaste


                    except:
                        print "No Electronic Waste Types"

                    try:
                        itemEwastePrevious = ''
                        for sr in ElectronicWaste:
                                for ewastetype in ElectronicWaste['La311ElectronicWaste']:
                                                itemEwaste =  ewastetype['ElectronicWestType']
                                                if itemEwastePrevious != itemEwaste:
                                                    itemEwastePrevious = itemEwaste
                    except:
                        print"No Ewaste items"


                    try:
                        iteminfoewasteprevious = ''
                        countEwastePrevious = ''
                        for sr in ElectronicWaste:
                                for ewastecount in ElectronicWaste['La311ElectronicWaste']:
                                                countEwaste = ewastecount['ItemCount']
                                                if countEwastePrevious != countEwaste:
                                                    countEwastePrevious = countEwaste
                                                    iteminfoewaste = '{0},  {1}, '.format(countEwastePrevious, itemEwastePrevious)
                                                    if iteminfoewasteprevious != iteminfoewaste:
                                                        iteminfoewasteprevious = iteminfoewaste

                    except:
                        print "No E-Waste Item Count"

                    try:
                        previousbulkycount = ' '
                        for sr in BulkyItem:
                                for bulkycount in BulkyItem['BulkyItem']:
                                                countBulky =  bulkycount['BulkyItemCount']
                                                if previousbulkycount != countBulky:
                                                    previousbulkycount =  countBulky
                    except:
                        print "No bulky counts"

                    try:
                        previousbulkyitem = ''
                        for sr in BulkyItem:
                                for bulkyitem in BulkyItem['BulkyItem']:
                                                        itemBulky =  bulkyitem['BulkyItemType']
                                                        if previousbulkyitem != itemBulky:
                                                            previousbulkyitem = itemBulky
                                                            listofdata = ''.join(previousbulkycount + ',' + previousbulkyitem)
                                                            BulkyItemInfo += '{0}, {1} '.format (previousbulkycount, previousbulkyitem)
                    except:
                        print "No Bulky Items"

                    try:
                        previousbulkylocation = ''
                        for sr in BulkyItem:
                            for bulkylocation in BulkyItem['BulkyItem']:
                                                    locationbulky =  bulkylocation['CollectionLocation']
                                                    if previousbulkyitem != locationbulky:
                                                        previousbulkylocation = itemBulky
                    except:
                        print "No Bulky Location"

                    try:

                        locationmhaprevious = ''
                        for sr in MHA:
                                for mhalocation in MHA['La311MetalHouseholdAppliancesPickup']:
                                                        locationmha =  mhalocation['CollectionLocation']
                                                        if locationmhaprevious != locationmha:
                                                            locationmhaprevious = locationmha
                    except:
                        print "No Metal Household Appliance Location"


                    try:
                        countmhaprevious = ''
                        for sr in MHA:
                                for mhacount in MHA['La311MetalHouseholdAppliancesPickup']:
                                                        countmha =  mhacount['HouseHoldItemCount']
                                                        if countmhaprevious != countmha:
                                                            countmhaprevious = countmha
                                                            MHAItemInfo += '{0}, {1} '.format (previousbulkycount, previousbulkyitem)
                    except:
                        print"No Household Item Count"

                    try:

                        itemmhaprevious = ''
                        for sr in MHA:
                                for mhaitem in MHA['La311MetalHouseholdAppliancesPickup']:
                                                        itemmha =  mhaitem['HouseholdItem']
                                                        if itemmhaprevious != itemmha:
                                                            itemmhaprevious = itemmha
                    except:
                        print"No Household Item"


                    try:

                        previousservicenotcomplete = ''
                        for sr in ServiceNotComplete:
                                for missedservice in ServiceNotComplete['La311ServiceNotComplete']:
                                                        servicemissed =  missedservice['MissedCollectionService']
                                                        if previousservicenotcomplete != servicemissed:
                                                            previousservicenotcomplete = servicemissed
                    except:
                        print "MissedCollection not Availalble"

                    try:
                        previousdarlocation = ''
                        for sr in DeadAnimalRemoval:
                                for darlocation in DeadAnimalRemoval['DeadAnimalRemoval']:
                                                        locationdar =  darlocation['CollectionLocation']
                                                        if previousdarlocation != locationdar:
                                                            previousdarlocation = locationdar
                    except:
                        print "DarLocation Not Avaialble"

                    try:
                        countdacprevious = ''
                        for sr in DeadAnimalRemoval:
                                for darcount in DeadAnimalRemoval['DeadAnimalRemoval']:
                                                        countdar =  darcount['DACItemCount']
                                                        if countdacprevious != countdar:
                                                            countdacprevious = countdar
                    except:
                        print "DacItemCount Not Found"

                    try:
                        typedacprevious = ''
                        for sr in DeadAnimalRemoval:
                                for dartype in DeadAnimalRemoval['DeadAnimalRemoval']:
                                                    typedac =  dartype['DACType']
                                                    if typedacprevious != typedac:
                                                        typedacprevious = typedac
                                                        DACItemInfo += '{0}, {1} '.format (typedacprevious, countdacprevious)
                    except:
                        print "DacType Not Found"

                    try:
                        previouslocationBrush = ''
                        for sr in BrushItems:
                                for brlocation in BrushItems['La311BrushItemsPickup']:
                                                        locationbrush =  brlocation['CollectionLocation']
                                                        if previouslocationBrush != locationbrush:
                                                            previouslocationBrush = locationbrush
                    except:
                        print "CollectionLocation Brush Items Not Found"

                    try:
                        previousbrushitem = ''
                        for sr in BrushItems:
                            for brtype in BrushItems['La311BrushItemsPickup']:
                                                    typebrush =  brtype['BrushType']
                                                    if previousbrushitem != typebrush:
                                                            previousbrushitem = typebrush
                    except:
                        print ""

                    try:
                            previousbrushcount = ''
                            for brcount in BrushItems['La311BrushItemsPickup']:
                                                    countbrush =  brcount['BrushTypeCount']
                                                    if previousbrushcount != countbrush:
                                                        previousbrushcount = countbrush
                    except:
                        print " "


                    try:
                        previousMoveInMoveOutLocation = ''
                        for sr in MoveInMoveOut:
                                for movelocation in MoveInMoveOut['La311MoveInMoveOut']:
                                                        locationmove =  movelocation['CollectionLocation']
                                                        if previousMoveInMoveOutLocation != locationmove:
                                                            previousMoveInMoveOutLocation = locationmove

                    except:
                        print " No Collection for move in move out"

                    try:
                        previousMovetype = ''
                        for sr in MoveInMoveOut:
                                for movetype in MoveInMoveOut["La311MoveInMoveOut"]:
                                                        typemove =  movetype['MoveType']
                                                        if previousMovetype != typemove:
                                                            previousMovetype = typemove

                    except:
                        print "Move Type Move in Move Out Not Found"


                    try:
                        previousmovecount = ''
                        for sr in MoveInMoveOut:
                                for moveitemcount in MoveInMoveOut["La311MoveInMoveOut":]:
                                                        coutmove =  moveitemcount['ItemCount']
                                                        if previousmovecount != coutmove:
                                                            previousmovecount = coutmove

                    except:
                        print "No Item Count for Move in Move Out Found"

                    try:
                        previousmanualLocation = ''
                        for sr in Manual:
                                for manuallocation in Manual["La311ManualPickup":]:
                                                        locationmanual =  manuallocation['collectionLocation']
                                                        if previousmanualcount != locationmanual:
                                                            previousmanualcount = locationmanual

                    except:
                        print "ManualLocation not found "
                    try:
                        previousmanualitem = ' '
                        for sr in Manual:
                                for manualpickitem in Manual["La311ManualPickup":]:
                                                        itempickmanual =  manualpickitem['ManualPickupItem']
                                                        if previousmanualitem != itempickmanual:
                                                            previousmanualitem = itempickmanual


                    except:
                        print "There is no manual item pickup"

                    try:
                        previousmanualiemcount = ''
                        for sr in Manual:
                                for manualcount in Manual["La311ManualPickup"]:
                                                        countmanual =  manualcount['ItemCount']
                                                        if previousmanualiemcount != countmanual:
                                                            previousmanualiemcount = countmanual
                    except:
                        print "No Count for manual items"

                    try:
                        previousillegallocation = ''
                        for sr in IllegalDumping:
                                for illegallocaltion in IllegalDumping["La311IllegalDumpingPickup"]:
                                                        locationillegal =  illegallocaltion['CollectionLocation']
                                                        if previousillegallocation != locationillegal:
                                                            previousillegallocation = locationillegal
                    except:
                       print "CollectionLocation for Illegal dumping not available"


                    ItemDesc = BulkyItemInfo + DACItemInfo
                    outputobjects= int(decoded2['Response']['NumOutputObjects'])

                    dt = np.dtype([('Address', 'U40'),
                                ('LatitudeShape', '<f8'),
                                ('LongitudeShape', '<f8'),
                                ('Latitude', '<f8'),
                                ('Longitude', '<f8'),
                                ('ReasonCode','U128'),
                                ('SRNumber', 'U40'),
                                ('FirstName', 'U40'),
                               ('LastName', 'U40'),
                                ('ResolutionCode','U128'),
                               ('HomePhone', 'U40'),
                                ('CreatedDate', 'U128'),
                                ('UpdatedDate', 'U128'),
                                ('ItemDesc','U128' ),

                                ])



                    
                    
                    items.append((SRAddress,
                                         x,

                                        y,
                                          x,
                                          y,
                                          ReasonCode,
                                          SRNumber,
                                         FirstName,
                                          LastName,
                                          ResolutionCode,
                                          HomePhone,
                                          CreatedDate,
                                          UpdatedDate,
                                          ItemDesc,

                                        ))
                    
                
                    sr = arcpy.SpatialReference(4326)
                    arr = np.array(items,dtype=dt)
                    NumPyArray = arcpy.da.NumPyArrayToFeatureClass(arr, fc, ['longitudeshape', 'latitudeshape'], sr)


                    arcpy.AddField_management(fc, "Create_Date", "DATE", '', 255)
                    arcpy.AddField_management(fc, "Update_Date", "DATE", '', 255)
                    arcpy.AddField_management(fc, "dateAndTime", "DATE", '', 255)

                    CreatedDate = "Create_Date"
                    UpdatedDate = "Update_Date"
                    DateAndTime = "dateAndTime"

                    cursor = arcpy.UpdateCursor(fc)
                    for row in cursor:
                        row.setValue(CreatedDate, row.getValue("CreatedDate"))
                    cursor.updateRow(row)

                    cursor = arcpy.UpdateCursor(fc)
                    for row in cursor:
                        row.setValue(UpdatedDate, row.getValue("UpdatedDate"))
                    cursor.updateRow(row)

                    cursor = arcpy.UpdateCursor(fc)
                    for row in cursor:
                        row.setValue(DateAndTime, row.getValue("jsonquerydate"))
                    cursor.updateRow(row)


                    strResult += "3DI to SANSTAR is successful for" + ' ' + str(Start)
                    success = True or False


                    rows = arcpy.InsertCursor(aTable)

                    for x in xrange(0, outputobjects):
                        row = rows.newRow()
                    row.setValue("Success", 'YES')
                    row.setValue("Fail", 'NO')
                    row.setValue("Time", Start)
                    rows.insertRow(row)

                    txtFile = open('C:\logs\sanstar_messages.txt', "a")
                    txtFile.write("service update is successful.\n" + str(Start))
                    txtFile.write("\n")
                    txtFile.write("service update is successful.\n")
                    txtFile.write("\n")
                    txtFile.close()

                else:
                        print "this works"
                        print json.dumps(decoded2, sort_keys=True, indent=4)

            except:
                print "this does not work"
    except arcpy.ExecuteError:
            strResult += arcpy.GetMessages()
            arcpy.AddMessage(strResult)

except:
            rows = arcpy.InsertCursor(aTable)
            outputobjects= int(decoded2['Response']['NumOutputObjects'])
            for x in xrange(0, outputobjects):
                row = rows.newRow()
            row.setValue("Success", 'NO')
            row.setValue("Fail", 'YES')
            row.setValue("Time", Start)
            rows.insertRow(row)
            logger.exception("Something has gone wrong!")
            print "the try has failed!"

            try:
                print "a"


            except:
                logger.exception("This works for the nested exception and fail has been logged in History_Table")
                rows = arcpy.InsertCursor(aTable)

            for x in xrange(0, outputobjects):
                row = rows.newRow()
            row.setValue("Success", 'NO')
            row.setValue("Fail", 'YES')
            row.setValue("Time", Start)
            rows.insertRow(row)

sendResultEmail(strResult, success)
print 'It took', time.time()-start, 'seconds.'


Output:
1
2
3
4
  Line 150
    except requests.exceptions.ConnectTimeout as e:
                                               ^
SyntaxError: invalid syntax


Create a new paste based on this one


Comments: