[ create a new paste ] login | about

Link: http://codepad.org/Gzb3px1R    [ 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
#!/usr/bin/python
# -*- coding: utf-8 -*-
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', 'pythonheat1'))
# 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 = 'pythonheat1' # 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 = 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)

    # begnining of arcpy-email try block
    # try:

if arcpy.Exists(fc):
    arcpy.Delete_management(fc)
try:
    r2
except requests.exceptions.ConnectTimeout, 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
    #
    # print now_minus_5
 # try:
 #    if last_run != now_minus_5:
 #        print "this block is activated"

items = []
for sr in decoded2['Response']['ListOfServiceRequest']['ServiceRequest'
        ]:
    SRAddress = sr['SRAddress']
    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')

    # try:
    #     for sr in ElectronicWaste:
    #             for ewastelocation in ElectronicWaste['La311ElectronicWaste']:
    #                                 locationewaste = ewastelocation['CollectionLocation']
    #                                 print locationewaste
    #             if locationewaste
    #
    # except:
    #     print "No Electronic Waste Types"

    iteminfo = ''
    try:
        itemEwastePrevious = None
        for sr in ElectronicWaste:
            for ewastetype in ElectronicWaste['La311ElectronicWaste']:
                itemEwaste = ewastetype['ElectronicWestType']
                if itemEwastePrevious != itemEwaste:
                    itemEwastePrevious = itemEwaste
    except:

        print 'No Ewaste items'

        # print ewastetype['ElectronicWestType']

#     try:
#         for sr in ElectronicWaste:
#                 for ewastecount in ElectronicWaste['La311ElectronicWaste']:
#                                    countEwaste =  ewastecount['ItemCount']
#     except:
#         print "No E-Waste Item Count"
#
#     try:
#         for sr in ElectronicWaste:
#                 for typeewaste in ElectronicWaste['La311ElectronicWaste']:
#                                         TypeEwaste =  typeewaste['Type']
#     except:
#         print "No E-Waste Type"
#

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

    try:
        for sr in BulkyItem:
            for bulkyitem in BulkyItem['BulkyItem']:
                itemBulky = bulkyitem['BulkyItemType']
                iteminfo += '{0},  {1}, '.format(itemBulky, countBulky)
    except:
        print 'No Bulky Items'

    try:
        for sr in BulkyItem:
            for bulkylocation in BulkyItem['BulkyItem']:
                locationbulky = bulkylocation['CollectionLocation']
    except:
        print 'No Bulky Location'

    try:
        for sr in BulkyItem:
            for bulkytype in BulkyItem['BulkyItem']:
                typebulky = bulkytype['Type']
    except:
        print 'No Bulky Types'

##     try:
##         for sr in MHA:
##                 for mhalocation in MHA['La311MetalHouseholdAppliancesPickup']:
##                                         locationmha =  mhalocation['CollectionLocation']
##     except:
##         print "No Metal Household Appliance Location"
##
##     try:
##         for sr in MHA:
##                 for mhacount in MHA['La311MetalHouseholdAppliancesPickup']:
##                                         countmha =  mhacount['HouseHoldItemCount']
##     except:
##         print"No Household Item Count"
##
##     try:
##         for sr in MHA:
##                 for mhaitem in MHA['La311MetalHouseholdAppliancesPickup']:
##                                         itemmha =  mhaitem['HouseholdItem']
##     except:
##         print"No Household Item"
##
##     try:
##         for sr in MHA:
##                 for mhatype in MHA['La311MetalHouseholdAppliancesPickup']:
##                                         typemha =  mhatype['Type']
##     except:
##         print "No MHA"
##
##
##     try:
##         for sr in ServiceNotComplete:
##                 for missedservice in ServiceNotComplete['La311ServiceNotComplete']:
##                                         servicemissed =  missedservice['MissedCollectionService']
##     except:
##         print "MissedCollection not Availalble"
##
##     try:
##         for sr in DeadAnimalRemoval:
##                 for dactype in DeadAnimalRemoval['DeadAnimalRemoval']:
##                                         DARTYPE =  dactype['Type']
##     except:
##         print "DeadAnimalRemovalType not found"
##
##     try:
##         for sr in DeadAnimalRemoval:
##                 for darlocation in DeadAnimalRemoval['DeadAnimalRemoval']:
##                                         locationdar =  darlocation['CollectionLocation']
##     except:
##         print "DarLocation Not Avaialble"
##
##     try:
##         for sr in DeadAnimalRemoval:
##                 for darcount in DeadAnimalRemoval['DeadAnimalRemoval']:
##                                         countdar =  darcount['DACItemCount']
##     except:
##         print "DacItemCount Not Found"
##
##     try:
##         for sr in DeadAnimalRemoval:
##                 for dartype in DeadAnimalRemoval['DeadAnimalRemoval']:
##                                         typedac =  dartype['DACType']
##     except:
##         print "DacType Not Found"
##
##
##         try:
##             for sr in BrushItems:
##                     for brlocation in BrushItems['La311BrushItemsPickup']:
##                                             locationbrush =  brlocation['CollectionLocation']
##         except:
##             print "CollectionLocation Brush Items Not Found"
##
##
##         try:
##             for sr in BrushItems:
##                 for brtype in BrushItems['La311BrushItemsPickup']:
##                                         typebrush =  brtype['BrushType']
##         except:
##             print "No Brush Type"
##
##         try:
##                 for brcount in BrushItems['La311BrushItemsPickup']:
##                                         countbrush =  brcount['BrushTypeCount']
##
##
##         except:
##             print " No Brush Item"
##         try:
##             for sr in BrushItems:
##                     for britem in BrushItems['La311BrushItemsPickup']:
##                                             itembr =  britem['Type']
##         except:
##             print " No Brush Item"
##         try:
##             for sr in MoveInMoveOut:
##                     for movelocation in MoveInMoveOut['La311MoveInMoveOut']:
##                                             locationmove =  movelocation['CollectionLocation']
##
##         except:
##             print " No Collection for move in move out"
##
##         try:
##             for sr in MoveInMoveOut:
##                     for movetype in MoveInMoveOut["La311MoveInMoveOut"]:
##                                             typemove =  movetype['MoveType']
##         except:
##             print "Move Type Move in Move Out Not Found"
##
##         try:
##             for sr in MoveInMoveOut:
##                     for movetype in MoveInMoveOut["La311MoveInMoveOut"]:
##                                             MOVETYPE =  movetype['Type']
##                                             print MOVETYPE
##         except:
##             print "No Move Type Move in Move Out Found"
##
##         try:
##             for sr in MoveInMoveOut:
##                     for moveitemcount in MoveInMoveOut["La311MoveInMoveOut":]:
##                                             coutmove =  moveitemcount['ItemCount']
##                                             print countmove
##         except:
##             print "No Item Count for Move in Move Out Found"
##
##         try:
##             for sr in Manual:
##                     for manuallocation in Manual["La311ManualPickup":]:
##                                             locationmanual =  manuallocation['collectionLocation']
##                                             print locationmanual
##         except:
##             print "ManualLocation not found "
##         try:
##             for sr in Manual:
##                     for manualpickitem in Manual["La311ManualPickup":]:
##                                             itempickmanual =  manualpickitem['ManualPickupItem']
##                                             print itempickmanual
##         except:
##             print "There is no manual item pickup"
##
##
##         try:
##             for sr in Manual:
##                     for manualcount in Manual["La311ManualPickup"]:
##                                             countmanual =  manualcount['ItemCount']
##                                             print countmanual
##         except:
##             print "No Count for manual items"
##
##
##         try:
##             for sr in Manual:
##                     for typemanual in Manual["La311ManualPickup"]:
##                                             MANUALTYPE =  typemanual['Type']
##                                             print MANUALTYPE
##         except:
##             print "No manual type"
##
##         try:
##             for sr in IllegalDumping:
##                     for illegallocaltion in IllegalDumping["La311IllegalDumpingPickup"]:
##                                             locationillegal =  illegallocaltion['CollectionLocation']
##                                             print locationillegal
##         except:
##            print "CollectionLocation for Illegal dumping not available"
##
##
##         try:
##             for sr in IllegalDumping:
##                     for illegaltype in IllegalDumping["La311IllegalDumpingPickup"]:
##                                             typeillegal =  illegaltype['Type']
##                                             print typeillegal
##         except:
##             print "No type illegal"
##
##
##     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'),
        ('EwasteItem', 'U128'),
        ('BulkyItem', 'U128'),
        ('ItemInfo', 'U128'),
        ('LocationBulky', 'U128'),
        ('BulkyType', 'U128'),
        ])

    items.append((
        SRAddress,
        x,
        y,
        x,
        y,
        ReasonCode,
        SRNumber,
        FirstName,
        LastName,
        ResolutionCode,
        HomePhone,
        CreatedDate,
        UpdatedDate,
        itemEwastePrevious,
        itemBulky,
        iteminfo,
        locationbulky,
        typebulky,
        ))

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

# print outputobjects

#
                    # 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"
#
#
#         #RESPONSE FOR 10 minutes

#     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
Traceback (most recent call last):
  Line 9, in <module>
    import json
ImportError: No module named json


Create a new paste based on this one


Comments: