def time_now_string(): """ 返回现在时间 """ return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
时间: 2023-08-29 20:12:10 浏览: 129
这段代码是一个函数,其功能是返回当前的本地时间,并将其格式化为字符串形式。具体来说,该函数使用了Python标准库中的time模块,调用了其中的strftime()函数。该函数可以将时间元组(由localtime()函数返回)格式化为指定的字符串。"%Y-%m-%d %H:%M:%S"是一个格式字符串,它指定了输出时间的具体格式。其中,%Y表示4位数的年份,%m表示2位数的月份,%d表示2位数的日期,%H表示2位数的小时数(24小时制),%M表示2位数的分钟数,%S表示2位数的秒数。该函数可以用于记录日志、生成文件名等需要时间戳的场合。
相关问题
coding=UTF-8 from flask import Flask, render_template, request, send_from_directory from werkzeug.utils import secure_filename from iconflow.model.colorizer import ReferenceBasedColorizer from skimage.feature import canny as get_canny_feature from torchvision import transforms from PIL import Image import os import datetime import torchvision import cv2 import numpy as np import torch import einops transform_Normalize = torchvision.transforms.Compose([ transforms.Normalize(0.5, 1.0)]) ALLOWED_EXTENSIONS = set([‘png’, ‘jpg’, ‘jpeg’]) app = Flask(name) train_model = ReferenceBasedColorizer() basepath = os.path.join( os.path.dirname(file), ‘images’) # 当前文件所在路径 def allowed_file(filename): return ‘.’ in filename and filename.rsplit(‘.’, 1)[1] in ALLOWED_EXTENSIONS def load_model(log_path=‘/mnt/4T/lzq/IconFlowPaper/checkpoints/normal_model.pt’): global train_model state = torch.load(log_path) train_model.load_state_dict(state[‘net’]) @app.route(“/”, methods=[“GET”, “POST”]) def hello(): if request.method == ‘GET’: return render_template(‘upload.html’) @app.route(‘/upload’, methods=[“GET”, “POST”]) def upload_lnk(): if request.method == ‘GET’: return render_template(‘upload.html’) if request.method == ‘POST’: try: file = request.files['uploadimg'] except Exception: return None if file and allowed_file(file.filename): format = "%Y-%m-%dT%H:%M:%S" now = datetime.datetime.utcnow().strftime(format) filename = now + '_' + file.filename filename = secure_filename(filename) basepath = os.path.join( os.path.dirname(file), ‘images’) # 当前文件所在路径 # upload_path = os.path.join(basepath,secure_filename(f.filename)) file.save(os.path.join(basepath, filename)) else: filename = None return filename @app.route(‘/download/string:filename’, methods=[‘GET’]) def download(filename): if request.method == “GET”: if os.path.isfile(os.path.join(basepath, filename)): return send_from_directory(basepath, filename, as_attachment=True) pass def get_contour(img): x = np.array(img) canny = 0 for layer in np.rollaxis(x, -1): canny |= get_canny_feature(layer, 0) canny = canny.astype(np.uint8) * 255 kernel = np.array([ [0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0], ], dtype=np.uint8) canny = cv2.dilate(canny, kernel) # canny = Image.fromarray(canny) return canny @app.route(‘/embedding//’, methods=[“GET”, “POST”]) def icontran(img, reference): global train_model if request.method == ‘POST’: imgPath = os.path.join(basepath, img) referencePath = os.path.join(basepath, reference) img = cv2.imread(imgPath) if img is None or img.size <= 0: return None contour = get_contour(img).astype(np.float32).copy() contour = 255 - contour reference = cv2.imread(referencePath).astype(np.float32) reference = cv2.cvtColor(reference, cv2.COLOR_BGR2RGB) reference = transform_Normalize(torch.from_numpy(reference).permute(2, 0, 1).unsqueeze(0).float()/ 255.0) contour = transform_Normalize(torch.from_numpy(contour).unsqueeze(0).unsqueeze(0).float()/ 255.0) train_model.eval() transfer = train_model(contour, reference) transfer = transfer.squeeze(0) transfer = (transfer + 0.5).clamp(0, 1).mul_(255).permute(1, 2, 0).type(torch.uint8).numpy() transfer = transfer.numpy() cv2.imwrite(imgPath, transfer) return basepath # success if name == “main”: load_model() app.run(host=‘10.21.16.144’, port=9999, debug=True) 用puthon写一个调用这个服务器的gui
这是一段 Python 代码,它使用 Flask 框架来创建一个网站应用。它还导入了一些需要使用的库,如 werkzeug、numpy、torch 等。该代码可以对图片进行一些处理,如调整亮度、色彩等。其中包括一个可以将黑白图片变成彩色图片的算法 train_model。同时,代码中使用了一些图像处理的函数和变换,如 canny 算法和 einops。最后,它可以将处理后的图片保存在指定的文件夹中,并在网页中展示出来。
把这段代码转化为python代码(package service import ( "encoding/json" "errors" "fmt" "gin-syudy/api/device/req" "gin-syudy/define" "gin-syudy/models" "gin-syudy/mqtt" "gin-syudy/tools/resp" "gin-syudy/utils" mq "github.com/eclipse/paho.mqtt.golang" "github.com/gin-gonic/gin" "log" "net/http" "strconv" "time" ) // DeviceController 控制设备 // @BasePath /api/v1 // @Description 启动对应设备 // @Tags 启动设备 // @param identity query string false "Identity" // @param controllerId query string false "controllerId" // @param controlState query string false "controlState" // @Success 200 {object} resp.Response "{"code":200,"data":[...]}" // @Failure 502 {object} resp.Response "{"code":502,"data":[...]}" // @Router /api/v1/device/start [Post] func DeviceController(c *gin.Context) { device := new(models.DeviceBasic) write := new(mqtt.Write) device.Identity = c.Query("identity") id, _ := strconv.Atoi(c.Query("controllerId")) fmt.Println(id) state, _ := strconv.Atoi(c.Query("controllerState")) fmt.Println(state) write.Id = uint32(id) write.State = uint32(state) if device.Identity == "" { resp.RespFail(c, http.StatusBadGateway, errors.New("必填参数为空"), resp.FoundFail) return } deviceBasic := device.GetTopicByIdentity() subTopic := "Device/" + deviceBasic.ItemName + "/" + deviceBasic.BridgeName + "/control" + deviceBasic.Secret fmt.Println(subTopic) sendTopic := "Host/" + deviceBasic.ItemName + "/" + deviceBasic.BridgeName + "/control" + deviceBasic.Secret fmt.Println(sendTopic) dataChan := make(chan *mqtt.StartDataResp, 1) mqtt.SubscribeMessage(subTopic, func(client mq.Client, message mq.Message) { fmt.Printf("MESSAGE : %s\n", message.Payload()) fmt.Printf("TOPIC : %s\n", message.Topic()) subscribeStartData := new(mqtt.StartDataResp) err := json.Unmarshal(message.Payload(), &subscribeStartData) if err != nil { resp.RespFail(c, http.StatusBadGateway, err, "回调函数格式不正确") return } dataChan <- subscribeStartData }) startData := new(mqtt.StartData) startData.SampTime = time.Now().String() startData.CommandID = utils.GetUUid() startData.Write = write data, _ := json.Marshal(startData) err := mqtt.SendMessage(sendTopic, data) if err != nil { resp.RespFail(c, http.StatusBadGateway, err, resp.FoundFail) return } responseMessage := <-dataChan err, _ = mqtt.Unsubscribe(sendTopic) if err != nil { resp.RespFail(c, http.StatusBadGateway, err, "取消订阅失败") return } resp.RespOK(c, responseMessage, "控制成功") })
以下是将给定的 Go 代码翻译为 Python 的代码:
```python
import json
import logging
import time
from http import HTTPStatus
import paho.mqtt.client as mqtt
from flask import jsonify, request
from service.models import DeviceBasic
from service.mqtt import SendMessage, SubscribeMessage, Unsubscribe
from service.tools.resp import RespFail, RespOK
from service.utils import GetUUid
# DeviceController
# 控制设备
# @BasePath /api/v1
# @Description 启动对应设备
# @Tags 启动设备
# @param identity query string false "Identity"
# @param controllerId query string false "controllerId"
# @param controlState query string false "controlState"
# @Success 200 {object} resp.Response "{"code":200,"data":[...]}"
# @Failure 502 {object} resp.Response "{"code":502,"data":[...]}"
# @Router /api/v1/device/start [Post]
def DeviceController():
device = DeviceBasic()
device.identity = request.args.get('identity', '')
id = int(request.args.get('controllerId', 0))
logging.debug(f"id: {id}")
state = int(request.args.get('controllerState', 0))
logging.debug(f"state: {state}")
write = Write()
write.id = id
write.state = state
if not device.identity:
RespFail(HTTPStatus.BAD_GATEWAY, errors=["必填参数为空"])
return
deviceBasic = device.GetTopicByIdentity()
subTopic = f"Device/{deviceBasic.ItemName}/{deviceBasic.BridgeName}/control{deviceBasic.Secret}"
logging.debug(f"subTopic: {subTopic}")
sendTopic = f"Host/{deviceBasic.ItemName}/{deviceBasic.BridgeName}/control{deviceBasic.Secret}"
logging.debug(f"sendTopic: {sendTopic}")
dataChan = []
def on_message(client, userdata, message):
logging.debug(f"MESSAGE : {message.payload}")
logging.debug(f"TOPIC : {message.topic}")
subscribeStartData = mqtt.StartDataResp()
try:
subscribeStartData = json.loads(message.payload)
except json.JSONDecodeError as e:
RespFail(HTTPStatus.BAD_GATEWAY, errors=[f"回调函数格式不正确: {str(e)}"])
return
dataChan.append(subscribeStartData)
mqtt.SubscribeMessage(subTopic, on_message)
startData = mqtt.StartData()
startData.SampTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
startData.CommandID = GetUUid()
startData.Write = write
data = json.dumps(startData, default=lambda obj: obj.__dict__, ensure_ascii=False)
err = SendMessage(sendTopic, data.encode())
if err:
RespFail(HTTPStatus.BAD_GATEWAY, errors=[err])
return
responseMessage = dataChan[0]
err = Unsubscribe(sendTopic)
if err:
RespFail(HTTPStatus.BAD_GATEWAY, errors=[f"取消订阅失败: {err}"])
return
RespOK(responseMessage, message="控制成功")
```
阅读全文