1ff27642 by 周伟奇

swagger2.0 & process command demo & pdf handler

1 parent 096de438
import time
import signal
from django.core.management import BaseCommand
class Command(BaseCommand):
def __init__(self):
super().__init__()
self.switch = True
signal.signal(signal.SIGTERM, self.signal_handler)
def signal_handler(self, sig, frame):
self.switch = False
print('get sig: {0}'.format(sig))
def handle(self, *args, **kwargs):
while self.switch:
print('process start')
time.sleep(5)
print('process success')
print('process stop')
import time
from django.core.management import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **kwargs):
while True:
print(time.time())
time.sleep(5)
......@@ -65,78 +65,20 @@ class DocView(GenericView):
return response.ok()
post.openapi_doc = '''
tags: [doc]
summary: POS系统上传文件信息
tags: [POS]
requestBody:
consumes: [application/json]
produces: [application/json]
parameters:
- in: body
name: body
required: true
content:
application/json:
schema:
type: object
properties:
applicationData:
description: 申请信息
type: object
properties:
applicationId:
description: 申请id
type: string
example: CH-B0011010101
applicantData:
description: 申请人信息
type: object
properties:
mainApplicantName:
description: 主申请人
type: string
example: 王明阳
coApplicantName:
description: 共同申请人
type: string
example: 王明月
guarantor1Name:
description: 担保人1
type: string
example: 王明日
guarantor2Name:
description: 担保人2
type: string
example: 王明雨
document:
description: 文件信息
type: object
properties:
documentName:
description: 文件名
type: string
example: CH-B0011010101王明阳申请表
documentScheme:
description: 文件格式?
type: string
example: CO00001
businessType:
description: 业务类型
type: string
example: HIL
uploadFinishTime:
description: 上传完成时间
type: string
example: '2020-09-01 12:21:11'
dataSource:
description: 数据源
type: string
example: POS
metadataVersionId:
description: 元数据版本ID
type: string
example: '8410480'
schema:
$ref: "#/definitions/Doc"
responses:
200:
description: ok
content:
application/json:
schema:
type: object
$ref: '#/components/schemas/ApiResponse'
schema:
$ref: '#/definitions/ApiResponse'
'''
......
base_part = '''
openapi: 3.0.0
swagger: "2.0"
info:
title: 接口文档
description: 宝马ocr/biz_logic接口文档
version: 1.0.0
servers:
- url: 'http://127.0.0.1:8000'
description: Development server
- url: 'http://staging-bmw-ocr.situdata.com'
description: sit
- url: 'http://127.0.0.1:8000'
description: uat
- url: 'http://127.0.0.1:8000'
description: prd
host: "staging-bmw-ocr.situdata.com"
basePath: "/"
tags:
- name: POS
description: POS系统交互
security:
- bearerAuth: []
- name: doc
description: 文件
schemes:
- "http"
'''
# scheme: bearer
security_schemes = '''
bearerAuth: # arbitrary name for the security scheme
type: http
scheme: bearer
bearerFormat: JWT
description: >
token过期标志
1. Response Headers中的WWW-Authenticate中的status
status: -1 Invalid Authorization header
status: -2 Signature has expired beacause of expire_time
status: -3 Error decoding signature
status: -4 Signature has expired beacause new signature is generated
status: 0 valid Authorization
status: 1 new create, only login would set
2. Response Body中的meta -> status == 1
# scheme: bearer
security_definitions = '''
'''
responses = '''
ErrorResponse:
description: 调用异常, 具体情况请参考`HTTP`状态码和`code`字段
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
schema:
$ref: '#/definitions/ApiResponse'
NoContent:
description: 后台接收请求,但是没有响应内容
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
schema:
$ref: '#/definitions/ApiResponse'
'''
parameters = ''
schemas = '''
definitions = '''
Doc:
type: object
required: [applicationData, applicantData, document]
properties:
applicationData:
description: 申请信息
type: object
required: [applicationId]
properties:
applicationId:
description: 申请id
type: string
example: CH-B0011010101
applicantData:
description: 申请人信息
type: object
required: [mainApplicantName, coApplicantName, guarantor1Name, guarantor2Name]
properties:
mainApplicantName:
description: 主申请人
type: string
example: 王明阳
coApplicantName:
description: 共同申请人
type: string
example: 王明月
guarantor1Name:
description: 担保人1
type: string
example: 王明日
guarantor2Name:
description: 担保人2
type: string
example: 王明雨
document:
description: 文件信息
type: object
required: [documentName, documentScheme, businessType, uploadFinishTime, dataSource, metadataVersionId]
properties:
documentName:
description: 文件名
type: string
example: CH-B0011010101王明阳申请表
documentScheme:
description: 文件格式?
type: string
example: CO00001
businessType:
description: 业务类型
type: string
example: HIL
uploadFinishTime:
description: 上传完成时间
type: string
example: '2020-09-01 12:21:11'
dataSource:
description: 数据源
type: string
example: POS
metadataVersionId:
description: 元数据版本ID
type: string
example: '8410480'
ApiResponse:
description: 响应对象,code字段用于表示响应的状态; data字段用于存放响应内容
type: object
required: [code, msg]
properties:
code:
type: integer
format: uint8
description: '0: success
1: need login
2: invalid params
3: internal error
4: object not exist
5: async wait
6: no permission
7: illegal operation'
1: need login
2: invalid params
3: internal error
4: object not exist
5: async wait
6: no permission
7: illegal operation'
example: 0
enum: [0, 1, 2, 3, 4, 5, 6, 7]
msg:
type: string
nullable: true
example: success
data:
oneOf:
- type: object
nullable: true
- type: integer
nullable: true
- type: array
nullable: true
Pagination:
description: 分页参数
type: object
properties:
current:
description: 当前页面
type: integer
total:
description: 所有元素个数
type: integer
page_size:
description: 页面大小
type: integer
required:
- current
- total
- pageSize
type: object
'''
\ No newline at end of file
......
......@@ -7,7 +7,7 @@ from django.urls.resolvers import get_resolver
import yaml
from yaml.scanner import ScannerError
from common.api_doc import (base_part, security_schemes, responses, schemas)
from common.api_doc import (base_part, security_definitions, responses, definitions)
_mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG
......@@ -73,18 +73,16 @@ class Command(BaseCommand):
except ScannerError as err:
raise Exception(
'failed to load doc: """%s"""\nerr: %s' % (doc, err))
if doc.get('parameters'):
for parameter in doc['parameters']:
if parameter['name'] in path_parameters:
doc['parameters'].pop(parameter)
# if doc.get('parameters'):
# for parameter in doc['parameters']:
# if parameter['name'] in path_parameters:
# doc['parameters'].pop(parameter)
api_doc_dct[url_path][method] = doc
doc_dct = yaml.load(base_part)
doc_dct['paths'] = api_doc_dct
doc_dct['components'] = {
'securitySchemes': yaml.load(security_schemes),
'responses': yaml.load(responses),
'schemas': yaml.load(schemas),
}
# doc_dct['securityDefinitions'] = yaml.load(security_definitions)
doc_dct['responses'] = yaml.load(responses)
doc_dct['definitions'] = yaml.load(definitions)
doc_str = yaml.dump(
doc_dct, default_flow_style=False, allow_unicode=True)
......
import fitz
import os
class PdfHandler:
def __init__(self, pdf_path):
self.pdf_path = pdf_path
self.pdf_name = os.path.splitext(os.path.basename(pdf_path))[0]
def to_pix_img(self, save_dir_path, zoom_x, zoom_y):
trans = fitz.Matrix(zoom_x, zoom_y).preRotate(0) # zoom factor 2 in each dimension
with fitz.Document(self.pdf_path) as pdf:
# print(pdf.metadata)
for page in pdf:
pm = page.getPixmap(matrix=trans, alpha=False) # 获得每一页的流对象
save_path = os.path.join(save_dir_path, '{0}_{1}.png'.format(self.pdf_name, page.number))
pm.writePNG(save_path)
def to_svg_img(self, save_dir_path):
with fitz.Document(self.pdf_path) as pdf:
for page in pdf:
svg = page.getSVGimage(matrix=fitz.Identity) # UTF-8 string svg
save_path = os.path.join(save_dir_path, '{0}_{1}.svg'.format(self.pdf_name, page.number))
with open(save_path, 'w') as f:
f.write(svg)
if __name__ == '__main__':
pdf_handler = PdfHandler('/Users/clay/Desktop/biz/pdf_test/test.pdf')
# pdf_handler.to_pix_img('/Users/clay/Desktop/biz/pdf_test/', 1.0, 1.0)
# pdf_handler.to_svg_img('/Users/clay/Desktop/biz/pdf_test/')
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!