def format(self, value): v = String.format(self, value) if (isinstance(v, dict)): return v try: json.loads(v) except Exception: msg = ("DictStr[%s] format ERROR" % (v)) raise MarshallingException(msg) return v
def format(self, value): v = String.format(self, value) try: dt = datetime.strptime(v, "%Y-%m-%d %H:%M:%S") dt = dt except Exception: try: dt = datetime.strptime(v, "%Y-%m-%dT%H:%M:%S") dt = dt except Exception: error_msg = ("Datetime[%s] format ERROR type." % (v)) raise MarshallingException(error_msg) v = v.replace("T", " ") return v
def format(self, value): v = String.format(self, value) if (v is None or 0 == len(str(v))): error_msg = ("Int list in len(0).") raise MarshallingException(error_msg) if (not isinstance(v, str)): error_msg = ("Int list NOT in string type.") raise MarshallingException(error_msg) v_list = [] for v_s in v.split(","): try: v_list.append(int(v_s)) except Exception: error_msg = ( "Int list items(seperated with ',') NOT in int type.") raise MarshallingException(error_msg) return v_list
class LogInResponseFields: resource_fields = dict(user=Integer(attribute='id'), name=String(attribute='full_name'), role=TypeResponseField(attribute='role'))
def __init__(self, data_field=None, *args, **kwargs): super().__init__(*args, **kwargs) self["code"] = Integer(default=0) self["message"] = String(default="success") self["data"] = Nested(data_field, default={})
from flask_restful.fields import String, Nested, List PersonParser = {"name": String()}
class DBUsersResponseFields: resource_fields = dict(user=Integer(attribute='id'), name=String(attribute='full_name'), role=Integer(attribute='_role'))
parser_put.add_argument("jobType", dest="job_type", type=str, choices=[f"{JOB_TYPE_CLI}", f"{JOB_TYPE_SCRIPT}"], help=f"请输入正确的任务类型,[{JOB_TYPE_CLI}|{JOB_TYPE_SCRIPT}]") parser_put.add_argument("jobCmd", dest="job_cmd", type=str, help="请输入任务运行命令, 如 python test.py") parser_put.add_argument("timeData", dest="time_data", type=str, help="请输入执行时间,如 0 5 * * *") parser_put.add_argument("createdBy", dest="created_by", type=str, help="请输入需求人") parser_put.add_argument("category", dest="category", type=str, help="请输入任务所属业务,[mes|erp|warranty|radar|pms|stopcard|...]") # 文件类型 parser_put.add_argument("file", type=FileStorage, help="请上传文件", location=["files"]) parser_put.add_argument("desc", dest="desc", type=str, help="请输入任务描述") # ============================================== [ parser done ] ============================================== post_fields = { "jobName": String(attribute="job_name"), "job_type": String(attribute="job_type"), "jobCmd": String(attribute="job_cmd"), "timeStyle": String(attribute="time_style"), "timeData": String(attribute="time_data") } posts_fields = { "status": Integer, "msg": String, "total": Integer, "data": List(Nested(post_fields)) } job_fields = { "jobName": String(attribute="job_name"),
@Created on : 2020/5/22 15:40 -------------------------------------- """ from flask_restful import Resource, marshal from flask_restful.fields import String, Integer, DateTime, Nested, List from flask_restful.reqparse import RequestParser from App.models.logs import RunningLog from App.setting import HTTP_OK, HTTP_QUERY_ERROR, MSG_JOB_QUERY_SUCCESS, MSG_JOB_QUERY_FAILED parser_logs = RequestParser(trim=True) parser_logs.add_argument("total", type=int, required=True, help="查询正确的查询数据量") log_fields_running = { "jobName": String(attribute="job_name"), "jobCmd": String(attribute="job_cmd"), "startDate": DateTime(attribute="start_date", dt_format="iso8601"), "endDate": DateTime(attribute="end_date", dt_format="iso8601"), "returnCode": Integer(attribute="return_code"), "stdout": String, "stderr": String } logs_fields_running = { "status": Integer, "msg": String, "total": Integer, "data": List(Nested(log_fields_running)) }
from .auth import * from flask_restful.fields import Integer, String import os error_fields = { "code": Integer(default=404), "message": String(default="Not Found Resource") } common_response = ResponseField() class StaticUrl(Raw): def format(self, value): return 'http://39.97.113.252:8080/static/' + value
class MeasurementResource(ResourceBase): db_table = Measurement measurement_file = { "label": String, "path": String( attribute=lambda x: "files/measurement/{}/{}".format( x.measurement_id, x.path ) ), } fields = { "id": Integer, "label": String, "start_date": String, "end_date": String, "meta_data": Raw, "files": List(Nested(measurement_file)), "jobs": List(IDField), } def get(self, id_): """ Receive a measurement --- summary: Find a measurement by ID tags: - measurements parameters: - name: id in: path description: ID of measurement to return required: true schema: type: integer responses: 200: description: successful operation content: application/json: schema: $ref: "#/components/schemas/Measurement" 400: description: Invalid ID supplied 404: description: Measurement not found """ try: resource = self.get_resource(id_) except (ResourceInvalidInputException, ResourceNotFoundException) as e: return {"status": str(e)}, e.response_code return self.dump_resource(resource), 200 def delete(self, id_): """ Delete a measurement --- summary: Deletes a measurement tags: - measurements parameters: - name: id in: path description: ID of measurement to return required: true schema: type: integer responses: 200: description: Measurement deleted and returned content: application/json: schema: $ref: "#/components/schemas/Measurement" 400: description: Invalid ID supplied 404: description: Measurement not found 405: description: Cannot delete measurement associated with a job """ try: resource = self.get_resource(id_) except (ResourceInvalidInputException, ResourceNotFoundException) as e: return {"status": str(e)}, e.response_code try: return self.delete_resource( current_app.config["MEASUREMENT_FILES_FOLDER"], resource ) except ResourceForbiddenActionException as e: return {"status": str(e)}, e.response_code def put(self, id_): """ Update the basic information about a measurement --- summary: Updates a measurement with new data tags: - measurements parameters: - name: id in: path description: ID of measurement to return required: true schema: type: integer requestBody: content: multipart/form-data: schema: properties: start_date: type: string format: date-time end_date: type: string format: date-time label: type: string meta_data: type: string responses: 200: description: Measurement updated and returned content: application/json: schema: $ref: "#/components/schemas/Measurement" 400: description: Invalid ID supplied or invalid input 404: description: Measurement not found """ try: resource = self.get_resource(id_) except (ResourceInvalidInputException, ResourceNotFoundException) as e: return {"status": str(e)}, e.response_code try: self._update_measurement(resource) except ResourceInvalidInputException as e: return {"status": str(e)}, e.response_code return self.dump_resource(resource), 200 def _update_measurement(self, resource): start_date, end_date = self.parse_dates( str(resource.start_date), str(resource.end_date) ) resource.start_date = start_date resource.end_date = end_date resource.label = request.form.get("label", resource.label) self.load_metadata(request.form.get("meta_data", "{}"), resource) db.session.commit() @staticmethod def parse_dates(start=None, end=None): try: start_date = date_parser(request.form.get("start_date", start)) end_date = date_parser(request.form.get("end_date", end)) except ValueError as e: raise ResourceInvalidInputException(str(e)) if end_date < start_date: raise ResourceInvalidInputException("end date < start date") return start_date, end_date
class JobResource(ResourceBase): db_table = Job job_inputfile = { "label": String, "value": String(attribute=lambda x: make_input_value(x)), } job_outputfile = { "label": String, "path": String(attribute=lambda x: "files/job/{}/output/{}".format( x.job.id, x.path)), } fields = { "id": Integer, "label": String, "date": String(attribute=lambda x: x.date.strftime("%Y-%m-%d %H:%M")), "status": String, "log": String(attribute=lambda x: "files/job/{}/{}".format(x.id, x.log) if x.log else ""), "analysis": IDField, "measurement": IDField, "input": List(Nested(job_inputfile)), "table_output": List(Nested(job_outputfile)), "figure_output": List(Nested(job_outputfile)), "reports": List(JobReportFile), } def get(self, id_): """ Receive a job --- summary: Find a job by ID tags: - jobs parameters: - name: id in: path description: ID of job to return required: true schema: type: integer responses: 200: description: successful operation content: application/json: schema: $ref: "#/components/schemas/Job" 400: description: Invalid ID supplied 404: description: Job not found """ try: resource = self.get_resource(id_) except (ResourceInvalidInputException, ResourceNotFoundException) as e: return {"status": str(e)}, e.response_code return self.dump_resource(resource), 200 def delete(self, id_): """ Delete a job --- summary: Deletes a job tags: - jobs parameters: - name: id in: path description: ID of job to delete required: true schema: type: integer responses: 200: description: Job deleted and returned content: application/json: schema: $ref: "#/components/schemas/Job" 400: description: Invalid ID supplied 404: description: Job not found """ try: resource = self.get_resource(id_) except (ResourceInvalidInputException, ResourceNotFoundException) as e: return {"status": str(e)}, e.response_code try: return self.delete_resource(current_app.config["JOB_FILES_FOLDER"], resource) except ResourceForbiddenActionException as e: return {"status": str(e)}, e.response_code
from . import ResponseField from flask_restful.fields import Integer, Nested, String, Boolean, DateTime, List from . import StaticUrl newsfield = { 'content': String(), 'imgs': List(StaticUrl()), 'time': DateTime(dt_format='iso8601'), 'uid': Integer, 'tid': Integer, 'liked': Boolean, 'likes': Integer, "comments": Integer, "avatar": StaticUrl, "sex": Integer, "username": String } createnewsfield = { 'uid': Integer, 'tid': Integer } newslist = { "news": [] } newslike = { 'tid': Integer, 'uid': Integer, 'likes': Integer, 'liked': Boolean(default=False) }