Django logging with dynamic name - python

I'm trying to create logs in my django project, but i want a log with a different filename for each execution. What i did so far is set it up like it's written here, but this creates one log and puts everything in it. I want a log per execution with a dynamic name, like instance name + date or something. Can this be done?
Edit: Code example of creating a scheduled task. (I think you will get what it does from this)
def create_schedule (inst):
path_task=os.path.join(os.path.join(os.path.dirname(__file__),os.pardir),os.pardir)
path_task=path_task[:len(path_task)-2]+'executeInstance.py'
tr='"py '+path_task + ' ' + str(inst.id)+'"'
tn='Inst ' + str(inst.id)
time=inst.schedule.time
if inst.schedule.scheduleType=='Weekly':
w_days=''
for day in inst.schedule.weekDays.all():
if w_days!='':
w_days=w_days+','
w_days=w_days+day.weekDay[:3].upper()
tn='"'+tn+'"'
cmd_sch='schtasks /create /tn ' + tn + ' /tr ' + tr + ' /sc weekly /d '+ w_days + ' /st ' + time + ' /RU SYSTEM'
result = subprocess.check_output(cmd_sch, shell=True)
And then catching an exception in executeInstance.py
except smtplib.SMTPDataError as e:
status_log='Error'
error_desc='Message size too big for your email server'
inst=Instance.objects.get(id=instance_id)
log=Log(instance=inst,status=status_log,errorDesc=error_desc,executionDate=datetime.now())
log.save()
logger.error(log)

Maybe try to play with time rotated log files? https://docs.python.org/2.7/library/logging.handlers.html#rotatingfilehandler

Related

Is there any way i can add sno to a file using openfile?

I want to add a serial no every time a new user information gets appended in.
def get_info():
op = open('sign in info win.txt', 'a')
serialno here is written to show where i want to add sno.
this piece of code is non working
op.write('information-no - ' + serialno + ' Name = ' + enter_name.get() + ' Password = ' + enter_password.get() + '\n')
op.close()
message = messagebox
message.showwarning(title='Saved !', message='Information Saved.')
The code in your question should already do the job, so if you're looking for a way to create a serial number perhaps you could use random.
import random
def generate_serial(length=10):
characters = list(range(0, 9))
serial = ''
for c in range(length):
serial += str( random.choice(characters) )
return serial
# Your existing code
def get_info():
serialno = generate_serial() # generate a new serialno each time
op = open('sign in info win.txt', 'a')
op.write('information-no - ' + serialno + ' Name = ' + enter_name.get() + ' Password = ' + enter_password.get() + '\n')
op.close()
message = messagebox
message.showwarning(title='Saved !', message='Information Saved.')
Here's a sample of what sort of serial numbers this would produce:
'5570344311'
'3852070084'
'5115012613'
'1655833704'
'6875243550'
Please note that while unlikely, it's entirely possible that generate_serial() will produce the same serial number for more than one user. Longer serial numbers or ones that can also contain letters reduce this probability, but if you want unique serials for every user this is not the way to go!

Python: How to store output in a shared folder path?

I am creating some QR images and wish to store in a shared folder path which requires username and password to access.
qrFolder = '\\cmbpnh01-srv-03\Tidata\12. IT Projects\QR Code Creation\QA QR Code Creation'
user = 'xxx\xxx'
password = 'xxx'
winCMD = 'NET USE ' + qrFolder + ' /User:' + user + ' ' + password
qrFilename = winCMD + " " + agentcode + "_" + outlet
img.save(qrFilename + imageExt)
Error: OSError: [Errno 22] Invalid argument: 'NET USE \cmbpnh01-srv-03\Tidata\n. IT Projects\QR Code Creation\QA QR Code Creation /User:xxx\xxx xxx ALVALLSR01_ALV0030138.png'
The objective is to store all QR codes inside the shared folder path which requires credentials. You could suggest any other approaches which can achieve this objective. Thanks!

How to get API call function that has multiple print statements to display in Flask?

I've got a Python script that checks an API for train data using requests and prints out relevant information based on information stored in dictionaries. This works fine in the console, but I'd like for it to be accessible online, for this I've been recommend to use Flask.
However, I can't get around using the Flask's function/returns in the routes to get the same output as I get in the console. I've gotten as far as getting the the requests module imported, but this throws up a HTTPError 400 when I use my actual code.
How would I go about getting the console output printed out into a page? Here is my current code:
import requests
import re
from darwin_token import DARWIN_KEY
jsonToken = DARWIN_KEY
train_station = {'work_station': 'whs', 'home_station': 'tth', 'connect_station': 'ecr'}
user_time = {'morning_time': ['0821', '0853'], 'evening_time': ['1733'], 'connect_time': ['0834', '0843']}
def darwinChecker(departure_station, arrival_station, user_time):
response = requests.get("https://huxley.apphb.com/all/" + str(departure_station) + "/to/" + str(arrival_station) + "/" + str(user_time), params={"accessToken": jsonToken})
response.raise_for_status() # this makes an error if something failed
data1 = response.json()
train_service = data1["trainServices"]
print('Departure Station: ' + str(data1['crs']))
print('Arrival Station: ' + str(data1['filtercrs']))
print('-' * 40)
try:
found_service = 0 # keeps track of services so note is generated if service not in user_time
for index, service in enumerate(train_service): # enumerate adds index value to train_service list
if service['sta'].replace(':', '') in user_time: # replaces sta time with values in user_time
found_service += 1 # increments for each service in user_time
print('Service RSID: ' + str(train_service[index]['rsid']))
print('Scheduled arrival time: ' + str(train_service[index]['sta']))
print('Scheduled departure time: ' + str(train_service[index]['std']))
print('Status: ' + str(train_service[index]['eta']))
print('-' * 40)
if service['eta'] == 'Cancelled':
print('The ' + str(train_service[index]['sta']) + ' service is cancelled.')
print('Previous train departure time: ' + str(train_service[index - 1]['sta']))
print('Previous train status: ' + str(train_service[index - 1]['eta']))
if found_service == 0: # if no service is found
print('The services currently available are not specified in user_time.')
except TypeError:
print('There is no train service data')
try:
NRCCRegex = re.compile('^(.*?)[\.!\?](?:\s|$)') # regex pulls all characters until hitting a . or ! or ?
myline = NRCCRegex.search(data1['nrccMessages'][0]['value']) # regex searches through nrccMessages
print('\nNRCC Messages: ' + myline.group(1) + '\n') # prints parsed NRCC message
except (TypeError, AttributeError) as error: # tuple catches multiple errors, AttributeError for None value
print('\nThere is no NRCC data currently available\n')
print('Morning Journey'.center(50, '='))
darwinChecker(train_station['home_station'], train_station['connect_station'], user_time['morning_time'])
The only thing I can think of is that I'd have to split each print statement in a function and a corresponding return?
Any help/clarification would be much appreciated!

Python subprocess doesn't run until calling process finished

EDIT 1 - added more code
I'm not sure that proc.communicate was needed, it was one of the suggestions I found from some other stackoverflow code.(Sorry I was tired last night and didn't think too much before asking the question.)
I should add that I am not an experienced coder (mechanical engineer) as you can probably tell from my code
In my Gui I have a button to call a subprocess
The subprocess (screenshot-cmd.exe) creates a png of a cropped screen shot but it won't actually produce the file until there is an error or if the button click event is over.
This makes me think that the subprocess is not actually run until the event is finished
I want to call the process several times after a single button press and move the files that it produces after each one is produced
if I use proc.wait(), the process hangs indefinitely.
How do I stop this?
# function to take a single image called 'fileName' and place it in directory 'dir'
def takeImage(dir,fileName):
# calculate the view to capture to get the whole display window in.
clientRect = win32gui.GetClientRect(win32gui.GetForegroundWindow())
windowRect = win32gui.GetWindowRect(win32gui.GetForegroundWindow())
print(windowRect)
windowSize = [windowRect[2]-windowRect[0],windowRect[3]-windowRect[1]]
print(windowSize)
print(clientRect)
diffSize = [windowSize[0] -clientRect[2], windowSize[1] - clientRect[3]]
lrbBorder = diffSize[0]/2
topBorder = diffSize[1] - lrbBorder
print("sizeDiff = " + str(diffSize))
windowName = win32gui.GetWindowText(win32gui.GetForegroundWindow())
handleId = win32gui.GetForegroundWindow()
leftMar = designLabel.GetPosition()[0] + lrbBorder
topMar = designLabel.GetPosition()[1] + topBorder + designLabel.GetSize()[1]
rightMar = leftMar + scene.width
bottMar = topMar+scene.height
margins = [leftMar,topMar,rightMar,bottMar]
print(margins)
# now print the view.
#command_line = r"screenshot-cmd -wt '" + windowName + "' -rc " + str(margins[0]) + " " + str(margins[1]) + " " + str(margins[2]) + " " + str(margins[3]) + " -o " + fileName
command_line = r"screenshot-cmd -wt '" + windowName + "' -rc " + str(margins[0]) + " " + str(margins[1]) + " " + str(margins[2]) + " " + str(margins[3]) + " -o " + fileName
print(command_line)
args = shlex.split(command_line)
proc = subprocess.Popen(args)
proc.wait()
wx.Yield()
if not os.path.isdir(dir):
os.makedirs(dir)
newPath = os.path.join(dir,fileName)
if os.path.exists(newPath):
os.remove(newPath)
oldPath = os.path.join(os.getcwd(), fileName)
print("Old Path: " + oldPath)
print("Exists: " + str(os.path.exists(oldPath)))
shutil.move(oldPath,newPath)
return
#event called upon clicking 'takeTenImag' button
def takeTenImgE(evt):
global designNo
global workingDirectory
global numDesigns
fileNameRoot = "test_"
fileExtention = ".png"
# check there are at least 10 designs
if numDesigns > 9 and os.path.exists(workingDirectory):
# find directory path to put images in
dir = os.path.join(workingDirectory, "images")
# for each design
for x in range(10):
print("design =" + str(designNo))
fileName = fileNameRoot + str(designNo) + fileExtention
print("------------------")
print("for x = " + str(x) + " " + fileName)
# create image and save
print(dir)
takeImage(dir,fileName)
#move to next design
wx.PostEvent(forwardDesign, wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, forwardDesign.GetId()) )
wx.Yield()
print("design =" + str(designNo))
return
takeTenImg = wx.Button(p, label='Take Ten Images', pos=(rb + visScaleText.GetSize()[0]+10,takeImg.GetPosition()[1]+5 +takeImg.GetSize()[1]), size = (100,30))
takeTenImg.Bind(wx.EVT_BUTTON, takeTenImgE)
https://code.google.com/p/screenshot-cmd/
Barnaby, you may be over-complicating your subprocess use. Popen is typically used for when you need to communicate with the process during the time it is running. From the sound of it, you don't need to do that, so might want to use a higher level function. See the docs on subprocess' various invocations, and perhaps try using the call method. You'll need shell=True, as detailed in SO questions such as this one.
I've found that the error is in my calling of subprocess.
I was using:
command_line = r"screenshot-cmd -wt '" + windowName + ...."
args = shlex.split(command_line)
subprocess.call(args,shell=True)
changing this to:
command_line = r"screenshot-cmd -wt '" + windowName + ...."
subprocess.call(command_line,shell=True)
solves the hang.
What is peculiar is that both options work when not inside a wx button click event(i.e. a python script launched from the command line), but only the second works when inside the wx button click event.
If anyone could enlighten me why that would be most appreciated.
EDIT:
upon further investigation, the hang is caused by trying to specify the active window in screenshot-cmd.
To solve this I find the position of the window using
windowRect = win32gui.GetWindowRect(win32gui.GetForegroundWindow())
and then use screenshot-cmd without specifying a window.
This solves all issues although it is unclear why this causes problems

Python program crashing

So I've designed a program that runs on a computer, looks for particular aspects of files that have been plaguing us, and deletes the files if a flag is passed. Unfortunately the program seems to be almost-randomly shutting down/crashing. I say almost-randomly, because the program always exits after it deletes a file, though it will commonly stay up after a success.
I've run a parallel Python program that counts upwards in the same intervals, but does nothing else. This program does not crash/exit, and stays open.
Is there perhaps a R/W access issue? I am running the program as administrator, so I'm not sure why that would be the case.
Here's the code:
import glob
import os
import time
import stat
#logging
import logging
logging.basicConfig(filename='disabledBots.log')
import datetime
runTimes = 0
currentPhp = 0
output = 0
output2 = 0
while runTimes >= 0:
#Cycles through .php files
openedProg = glob.glob('*.php')
openedProg = openedProg[currentPhp:currentPhp+1]
progInput = ''.join(openedProg)
if progInput != '':
theBot = open(progInput,'r')
#Singles out "$output" on this particular line and closes the process
readLines = theBot.readlines()
wholeLine = (readLines[-4])
output = wholeLine[4:11]
#Singles out "set_time_limit(0)"
wholeLine2 = (readLines[0])
output2 = wholeLine2[6:23]
theBot.close()
if progInput == '':
currentPhp = -1
#Kills the program if it matches the code
currentTime = datetime.datetime.now()
if output == '$output':
os.chmod(progInput, stat.S_IWRITE)
os.remove(progInput)
logging.warning(str(currentTime) +' ' + progInput + ' has been deleted. Please search for a faux httpd.exe process and kill it.')
currentPhp = 0
if output2 == 'set_time_limit(0)':
os.chmod(progInput, stat.S_IWRITE)
os.remove(progInput)
logging.warning(str(currentTime) +' ' + progInput + ' has been deleted. Please search for a faux httpd.exe process and kill it.')
currentPhp = 0
else:
currentPhp = currentPhp + 1
time.sleep(30)
#Prints the number of cycles
runTimes = runTimes + 1
logging.warning((str(currentTime) + ' botKiller2.0 has scanned '+ str(runTimes) + ' times.'))
print('botKiller3.0 has scanned ' + str(runTimes) + ' times.')
Firstly, it'll be hell of a lot easier to work out what's going on if you base your code around something like this...
for fname in glob.glob('*.php'):
with open(fname) as fin:
lines = fin.readlines()
if '$output' in lines[-4] or 'set_time_limit(0)' in lines[0]:
try:
os.remove(fname)
except IOError as e:
print "Couldn't remove:", fname
And err, that's not actually a secondly at the moment, your existing code is just too tricky to follow fullstop, let alone all the bits that could cause a strange error that we don't know yet!
if os.path.exists(progInput):
os.chmod(progInput, stat.S_IWRITE)
os.remove(progInput)
ALSO:
You never reset the output or output2 variables in the loop?
is this on purpose?

Categories

Resources