问题:导出文件时,如何将字节流返回给前端,前端通过blob方式获取

方法:
Tornado

import xlwt
from io import BytesIO

class ApiDownloadHandler(BaseHandler):
    @login_required()
    def post(self):
        # 设置响应头
        self.set_header('Content-Type', 'application/x-xls')
        # filename 不能为中文
        self.set_header('Content-Disposition', 'attachment; filename=download.xls')
        wb = xlwt.Workbook()
        ws = wb.add_sheet('Sheet1')
        style0 = xlwt.easyxf('font: name Microsoft YaHei Light, height 220; align: vert centre, horiz center')
        # title
        header = ['序号', '姓名', '年龄']
        for i in range(len(header)):
            ws.write(0, i, header[i], style0)
            ws.col(i).width = 4000
        sio = BytesIO()
        # 这点很重要,传给save函数的不是保存文件名,而是一个StringIO流
        wb.save(sio)
        self.write(sio.getvalue())

阅读全文

问题:方法中如何调用另一个类中__call__方法?

方法:

class foo(object):
    def __init__(self):
        self.name = 'python'

    def __call__(self, *args, **kwargs):
        print('hello%s'%self.name)

def run():
    instance = foo()
    instance()
    a = instance
    print dir(a)

阅读全文

问题:如何使用python对接cas统一认证系统,实现用户登录?

解决:使用模块python-cas

方法:

from cas import CASClient

cas_client = CASClient(
    version=3,
    service_url='http://xx.com/login?next=%2Fprofile',
    server_url='http://sso.xx.xx.cn/cas/'
)


@router.get("/", name="测试cas")
async def index():
    return RedirectResponse('/login')

阅读全文

问题:python使用threading实现线程时,如何调用异步函数?

解决:使用asyncio.run

方法:

async def import_users(db, temp_name):
    # 我的处理方法
    pass
lock = threading.Lock()
def thread_target():
    with lock:
        asyncio.run(import_users(db, name))

threads = [threading.Thread(target=thread_target, args=(db, temp.name)) for _ in range(10)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

阅读全文