本文整理汇总了Python中dataactcore.utils.jsonResponse.JsonResponse.error方法的典型用法代码示例。如果您正苦于以下问题:Python JsonResponse.error方法的具体用法?Python JsonResponse.error怎么用?Python JsonResponse.error使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dataactcore.utils.jsonResponse.JsonResponse
的用法示例。
在下文中一共展示了JsonResponse.error方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: delete_submission
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def delete_submission(submission):
""" Deletes all data associated with the specified submission
NOTE: THERE IS NO WAY TO UNDO THIS """
if submission.publish_status_id != PUBLISH_STATUS_DICT['unpublished']:
return JsonResponse.error(ValueError("Submissions that have been certified cannot be deleted"),
StatusCode.CLIENT_ERROR)
sess = GlobalDB.db().session
# Check if the submission has any jobs that are currently running, if so, do not allow deletion
jobs = sess.query(Job).filter(Job.submission_id == submission.submission_id,
Job.job_status_id == JOB_STATUS_DICT['running']).all()
if jobs:
return JsonResponse.error(ValueError("Submissions with running jobs cannot be deleted"),
StatusCode.CLIENT_ERROR)
sess.query(SubmissionSubTierAffiliation).filter(
SubmissionSubTierAffiliation.submission_id == submission.submission_id).delete(
synchronize_session=False)
sess.query(Submission).filter(Submission.submission_id == submission.submission_id).delete(
synchronize_session=False)
sess.expire_all()
return JsonResponse.create(StatusCode.OK, {"message": "Success"})
示例2: getErrorReportURLsForSubmission
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def getErrorReportURLsForSubmission(self):
"""
Gets the Signed URLs for download based on the submissionId
"""
try :
self.s3manager = s3UrlHandler()
safeDictionary = RequestDictionary(self.request)
submissionId = safeDictionary.getValue("submission_id")
responseDict ={}
for jobId in self.jobManager.getJobsBySubmission(submissionId):
if(self.jobManager.getJobType(jobId) == "csv_record_validation"):
if(not self.isLocal):
responseDict["job_"+str(jobId)+"_error_url"] = self.s3manager.getSignedUrl("errors",self.jobManager.getReportPath(jobId),"GET")
else:
path = os.path.join(self.serverPath, self.jobManager.getReportPath(jobId))
responseDict["job_"+str(jobId)+"_error_url"] = path
if(not self.isLocal):
crossFileReport = self.s3manager.getSignedUrl("errors",self.jobManager.getCrossFileReportPath(submissionId),"GET")
else:
crossFileReport = os.path.join(self.serverPath, self.jobManager.getCrossFileReportPath(submissionId))
responseDict["cross_file_error_url"] = crossFileReport
return JsonResponse.create(StatusCode.OK,responseDict)
except ResponseException as e:
return JsonResponse.error(e,StatusCode.CLIENT_ERROR)
except Exception as e:
# Unexpected exception, this is a 500 server error
return JsonResponse.error(e,StatusCode.INTERNAL_ERROR)
示例3: finalize
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def finalize(self):
""" Set upload job in job tracker database to finished, allowing dependent jobs to be started
Flask request should include key "upload_id", which holds the job_id for the file_upload job
Returns:
A flask response object, if successful just contains key "success" with value True, otherwise value is False
"""
responseDict = {}
try:
inputDictionary = RequestDictionary(self.request)
jobId = inputDictionary.getValue("upload_id")
# Compare user ID with user who submitted job, if no match return 400
job = self.jobManager.getJobById(jobId)
submission = self.jobManager.getSubmissionForJob(job)
if(submission.user_id != LoginSession.getName(session)):
# This user cannot finalize this job
raise ResponseException("Cannot finalize a job created by a different user", StatusCode.CLIENT_ERROR)
# Change job status to finished
if(self.jobManager.checkUploadType(jobId)):
self.jobManager.changeToFinished(jobId)
responseDict["success"] = True
return JsonResponse.create(StatusCode.OK,responseDict)
else:
raise ResponseException("Wrong job type for finalize route",StatusCode.CLIENT_ERROR)
except ( ValueError , TypeError ) as e:
return JsonResponse.error(e,StatusCode.CLIENT_ERROR)
except ResponseException as e:
return JsonResponse.error(e,e.status)
except Exception as e:
# Unexpected exception, this is a 500 server error
return JsonResponse.error(e,StatusCode.INTERNAL_ERROR)
示例4: resetPassword
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def resetPassword(self,system_email,session):
"""
Remove old password and email user a token to set a new password. Request should have key "email"
arguments:
system_email -- (string) email used to send messages
session -- (Session) object from flask
"""
requestDict = RequestDictionary(self.request)
if(not (requestDict.exists("email"))):
# Don't have the keys we need in request
exc = ResponseException("Reset password route requires key 'email'",StatusCode.CLIENT_ERROR)
return JsonResponse.error(exc,exc.status)
# Get user object
try:
user = self.interfaces.userDb.getUserByEmail(requestDict.getValue("email"))
except Exception as e:
exc = ResponseException("Unknown Error",StatusCode.CLIENT_ERROR,ValueError)
return JsonResponse.error(exc,exc.status)
LoginSession.logout(session)
self.interfaces.userDb.session.commit()
email = requestDict.getValue("email")
# Send email with token
emailToken = sesEmail.createToken(email,self.interfaces.userDb,"password_reset")
link= "".join([ AccountHandler.FRONT_END,'#/forgotpassword/',emailToken])
emailTemplate = { '[URL]':link}
newEmail = sesEmail(user.email, system_email,templateType="reset_password",parameters=emailTemplate,database=self.interfaces.userDb)
newEmail.send()
# Return success message
return JsonResponse.create(StatusCode.OK,{"message":"Password reset"})
示例5: createEmailConfirmation
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def createEmailConfirmation(self,system_email,session):
"""
Creates user record and email
arguments:
system_email -- (string) email used to send messages
session -- (Session) object from flask
"""
requestFields = RequestDictionary(self.request)
if(not requestFields.exists("email")):
exc = ResponseException("Request body must include email", StatusCode.CLIENT_ERROR)
return JsonResponse.error(exc,exc.status)
email = requestFields.getValue("email")
if( not re.match("[^@][email protected][^@]+\.[^@]+",email)) :
return JsonResponse.error(ValueError("Invalid Email Format"),StatusCode.CLIENT_ERROR)
try :
user = self.interfaces.userDb.getUserByEmail(requestFields.getValue("email"))
except ResponseException as e:
self.interfaces.userDb.addUnconfirmedEmail(email)
else:
if(not (user.user_status_id == self.interfaces.userDb.getUserStatusId("awaiting_confirmation") or user.user_status_id == self.interfaces.userDb.getUserStatusId("email_confirmed"))):
exc = ResponseException("User already registered", StatusCode.CLIENT_ERROR)
return JsonResponse.error(exc,exc.status)
emailToken = sesEmail.createToken(email,self.interfaces.userDb,"validate_email")
link= "".join([AccountHandler.FRONT_END,'#/registration/',emailToken])
emailTemplate = {'[USER]': email, '[URL]':link}
newEmail = sesEmail(email, system_email,templateType="validate_email",parameters=emailTemplate,database=self.interfaces.userDb)
newEmail.send()
return JsonResponse.create(StatusCode.OK,{"message":"Email Sent"})
示例6: run_instance_function
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def run_instance_function(
accountManager, accountFunction, getSystemEmail=False, getSession=False, getUser=False, getCredentials=False
):
""" Standard error handling around each route """
interfaces = InterfaceHolder()
try:
accountManager.addInterfaces(interfaces)
if getSystemEmail and getSession:
return accountFunction(RouteUtils.SYSTEM_EMAIL, session)
elif getSystemEmail:
return accountFunction(RouteUtils.SYSTEM_EMAIL)
elif getSession:
return accountFunction(session)
elif getUser:
if getCredentials:
return accountFunction(LoginSession.getName(session), RouteUtils.CREATE_CREDENTIALS)
else:
# Currently no functions with user but not credentials flag
raise ValueError("Invalid combination of flags to run_instance_function")
else:
return accountFunction()
except ResponseException as e:
return JsonResponse.error(e, e.status)
except Exception as e:
exc = ResponseException(str(e), StatusCode.INTERNAL_ERROR, type(e))
return JsonResponse.error(exc, exc.status)
finally:
interfaces.close()
示例7: uploadFile
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def uploadFile(self):
"""saves a file and returns the saved path"""
try:
if(self.isLocal):
uploadedFile = request.files['file']
if(uploadedFile):
seconds = int((datetime.utcnow()-datetime(1970,1,1)).total_seconds())
filename = "".join([str(seconds),"_", secure_filename(uploadedFile.filename)])
path = os.path.join(self.serverPath, filename)
uploadedFile.save(path)
returnDict = {"path":path}
return JsonResponse.create(StatusCode.OK,returnDict)
else:
exc = ResponseException("Failure to read file", StatusCode.CLIENT_ERROR)
return JsonResponse.error(exc,exc.status)
else :
exc = ResponseException("Route Only Valid For Local Installs", StatusCode.CLIENT_ERROR)
return JsonResponse.error(exc,exc.status)
except ( ValueError , TypeError ) as e:
return JsonResponse.error(e,StatusCode.CLIENT_ERROR)
except ResponseException as e:
return JsonResponse.error(e,e.status)
except Exception as e:
# Unexpected exception, this is a 500 server error
return JsonResponse.error(e,StatusCode.INTERNAL_ERROR)
示例8: getErrorMetrics
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def getErrorMetrics(self) :
""" Returns an Http response object containing error information for every validation job in specified submission """
responseDict = {}
returnDict = {}
try:
safeDictionary = RequestDictionary(self.request)
submission_id = safeDictionary.getValue("submission_id")
# Check if user has permission to specified submission
self.checkSubmissionPermission(self.jobManager.getSubmissionById(submission_id))
jobIds = self.jobManager.getJobsBySubmission(submission_id)
for currentId in jobIds :
if(self.jobManager.getJobType(currentId) == "csv_record_validation"):
fileName = self.jobManager.getFileType(currentId)
dataList = self.interfaces.errorDb.getErrorMetricsByJobId(currentId)
returnDict[fileName] = dataList
return JsonResponse.create(StatusCode.OK,returnDict)
except ( ValueError , TypeError ) as e:
return JsonResponse.error(e,StatusCode.CLIENT_ERROR)
except ResponseException as e:
return JsonResponse.error(e,e.status)
except Exception as e:
# Unexpected exception, this is a 500 server error
return JsonResponse.error(e,StatusCode.INTERNAL_ERROR)
示例9: setSkipGuide
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def setSkipGuide(self, session):
""" Set current user's skip guide parameter """
uid = session["name"]
userDb = self.interfaces.userDb
user = userDb.getUserByUID(uid)
requestDict = RequestDictionary(self.request)
if not requestDict.exists("skip_guide"):
exc = ResponseException("Must include skip_guide parameter", StatusCode.CLIENT_ERROR)
return JsonResponse.error(exc, exc.status)
skipGuide = requestDict.getValue("skip_guide")
if type(skipGuide) == type(True):
# param is a bool
user.skip_guide = skipGuide
elif type(skipGuide) == type("string"):
# param is a string, allow "true" or "false"
if skipGuide.lower() == "true":
user.skip_guide = True
elif skipGuide.lower() == "false":
user.skip_guide = False
else:
exc = ResponseException("skip_guide must be true or false", StatusCode.CLIENT_ERROR)
return JsonResponse.error(exc, exc.status)
else:
exc = ResponseException("skip_guide must be a boolean", StatusCode.CLIENT_ERROR)
return JsonResponse.error(exc, exc.status)
userDb.session.commit()
return JsonResponse.create(StatusCode.OK,{"message":"skip_guide set successfully","skip_guide":skipGuide})
示例10: resetPassword
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def resetPassword(self,system_email,session):
"""
Remove old password and email user a token to set a new password. Request should have key "email"
arguments:
system_email -- (string) email used to send messages
session -- (Session) object from flask
"""
requestDict = RequestDictionary(self.request)
if(not (requestDict.exists("email"))):
# Don't have the keys we need in request
exc = ResponseException("Reset password route requires key 'email'",StatusCode.CLIENT_ERROR)
return JsonResponse.error(exc,exc.status)
# Get user object
try:
user = self.interfaces.userDb.getUserByEmail(requestDict.getValue("email"))
except Exception as e:
exc = ResponseException("Unknown Error",StatusCode.CLIENT_ERROR,ValueError)
return JsonResponse.error(exc,exc.status)
email = requestDict.getValue("email")
LoginSession.logout(session)
self.sendResetPasswordEmail(user, system_email, email)
# Return success message
return JsonResponse.create(StatusCode.OK,{"message":"Password reset"})
示例11: listUsersWithStatus
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def listUsersWithStatus(self):
""" List all users with the specified status. Associated request body must have key 'status' """
requestDict = RequestDictionary(self.request)
if(not (requestDict.exists("status"))):
# Missing a required field, return 400
exc = ResponseException("Request body must include status", StatusCode.CLIENT_ERROR)
return JsonResponse.error(exc,exc.status)
current_user = self.interfaces.userDb.getUserByUID(flaskSession["name"])
try:
if self.interfaces.userDb.hasPermission(current_user, "agency_admin"):
users = self.interfaces.userDb.getUsersByStatus(requestDict.getValue("status"), current_user.cgac_code)
else:
users = self.interfaces.userDb.getUsersByStatus(requestDict.getValue("status"))
except ValueError as e:
# Client provided a bad status
exc = ResponseException(str(e),StatusCode.CLIENT_ERROR,ValueError)
return JsonResponse.error(exc,exc.status)
userInfo = []
for user in users:
agency_name = self.interfaces.validationDb.getAgencyName(user.cgac_code)
thisInfo = {"name":user.name, "title":user.title, "agency_name":agency_name, "cgac_code":user.cgac_code,
"email":user.email, "id":user.user_id }
userInfo.append(thisInfo)
return JsonResponse.create(StatusCode.OK,{"users":userInfo})
示例12: get_submission_data
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def get_submission_data(submission, file_type=''):
""" Get data for the submission specified
Args:
submission: submission to retrieve metadata for
file_type: the type of job to retrieve metadata for
Returns:
JsonResponse containing the error information or the object containing metadata for all relevant file types
"""
sess = GlobalDB.db().session
file_type = file_type.lower()
# Make sure the file type provided is valid
if file_type and file_type not in FILE_TYPE_DICT and file_type != 'cross':
return JsonResponse.error(ValueError(file_type + ' is not a valid file type'), StatusCode.CLIENT_ERROR)
# Make sure the file type provided is valid for the submission type
is_fabs = submission.d2_submission
if file_type and (is_fabs and file_type != 'fabs') or (not is_fabs and file_type == 'fabs'):
return JsonResponse.error(ValueError(file_type + ' is not a valid file type for this submission'),
StatusCode.CLIENT_ERROR)
job_query = sess.query(Job).filter(Job.submission_id == submission.submission_id)
if not file_type:
relevant_job_types = (JOB_TYPE_DICT['csv_record_validation'], JOB_TYPE_DICT['validation'])
job_query = job_query.filter(Job.job_type_id.in_(relevant_job_types))
elif file_type == 'cross':
job_query = job_query.filter(Job.job_type_id == JOB_TYPE_DICT['validation'])
else:
job_query = job_query.filter(Job.file_type_id == FILE_TYPE_DICT[file_type])
job_dict = {'jobs': [job_to_dict(job) for job in job_query]}
return JsonResponse.create(StatusCode.OK, job_dict)
示例13: login
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def login(self,session):
"""
Logs a user in if their password matches
arguments:
session -- (Session) object from flask
return the reponse object
"""
try:
safeDictionary = RequestDictionary(self.request)
username = safeDictionary.getValue('username')
password = safeDictionary.getValue('password')
try:
user = self.interfaces.userDb.getUserByEmail(username)
except Exception as e:
raise ValueError("user name and or password invalid")
if(not self.interfaces.userDb.checkStatus(user,"approved")):
raise ValueError("user name and or password invalid")
# Only check if user is active after they've logged in for the first time
if user.last_login_date is not None and not self.isUserActive(user):
raise ValueError("Your account has expired. Please contact an administrator.")
try:
if(self.interfaces.userDb.checkPassword(user,password,self.bcrypt)):
# We have a valid login
LoginSession.login(session,user.user_id)
permissionList = []
for permission in self.interfaces.userDb.getPermssionList():
if(self.interfaces.userDb.hasPermission(user, permission.name)):
permissionList.append(permission.permission_type_id)
self.interfaces.userDb.updateLastLogin(user)
return JsonResponse.create(StatusCode.OK,{"message":"Login successful","user_id": int(user.user_id),"name":user.name,"title":user.title ,"agency":user.agency, "permissions" : permissionList})
else :
raise ValueError("user name and or password invalid")
except Exception as e:
LoginSession.logout(session)
raise ValueError("user name and or password invalid")
except (TypeError, KeyError, NotImplementedError) as e:
# Return a 400 with appropriate message
return JsonResponse.error(e,StatusCode.CLIENT_ERROR)
except ValueError as e:
# Return a 401 for login denied
return JsonResponse.error(e,StatusCode.LOGIN_REQUIRED)
except Exception as e:
# Return 500
return JsonResponse.error(e,StatusCode.INTERNAL_ERROR)
return self.response
示例14: submission_list_certifications
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def submission_list_certifications(submission):
if submission.d2_submission:
return JsonResponse.error(ValueError("FABS submissions do not have a certification history"),
StatusCode.CLIENT_ERROR)
sess = GlobalDB.db().session
certify_history = sess.query(CertifyHistory).filter_by(submission_id=submission.submission_id)
if certify_history.count() == 0:
return JsonResponse.error(ValueError("This submission has no certification history"),
StatusCode.CLIENT_ERROR)
return list_certifications(submission)
示例15: login
# 需要导入模块: from dataactcore.utils.jsonResponse import JsonResponse [as 别名]
# 或者: from dataactcore.utils.jsonResponse.JsonResponse import error [as 别名]
def login(self, session):
"""
Logs a user in if their password matches
arguments:
session -- (Session) object from flask
return the response object
"""
try:
sess = GlobalDB.db().session
safe_dictionary = RequestDictionary(self.request)
username = safe_dictionary.get_value('username')
password = safe_dictionary.get_value('password')
try:
user = sess.query(User).filter(func.lower(User.email) == func.lower(username)).one()
except Exception:
raise ValueError("Invalid username and/or password")
try:
if check_correct_password(user, password, self.bcrypt):
# We have a valid login
return self.create_session_and_response(session, user)
else:
raise ValueError("Invalid username and/or password")
except ValueError as ve:
LoginSession.logout(session)
raise ve
except Exception as e:
LoginSession.logout(session)
raise e
except (TypeError, KeyError, NotImplementedError) as e:
# Return a 400 with appropriate message
return JsonResponse.error(e, StatusCode.CLIENT_ERROR)
except ValueError as e:
# Return a 401 for login denied
return JsonResponse.error(e, StatusCode.LOGIN_REQUIRED)
except Exception as e:
# Return 500
return JsonResponse.error(e, StatusCode.INTERNAL_ERROR)