Blender学堂   

【首页】

Blender使用python:构建http服务器


【2024-04-09】 【Blender学堂】


Blender可以使用python构建一个http服务器,

用于和其它blender应用(或者其它程序开发的网络应用)之间进行信息交互。


"""
Created on Fri Jun 23 08:13:43 2017

@author: dc
"""

import http.server as hs

import bpy

import sys, os

import threading

from time import ctime,sleep

import random


def movec(name):
a=bpy.data.objects[name]
x=random.randint(0,2)
y=random.randint(0,2)
a.location[0]=x
a.location[1]=y

class ServerException(Exception):

#´´´´´server iner error´´´

pass

class RequestHandler(hs.BaseHTTPRequestHandler):

def send_content(self, page, status = 200):

self.send_response(status)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(len(page)))
self.end_headers()
self.wfile.write(bytes(page, encoding = ´utf-8´))
#print(page)
movec(´chair.001´)
movec(´chair.002´)

def do_GET(self):

#two exception error:path error, file error
try:

# get path
full_path = os.getcwd() + self.path

# no path
if not os.path.exists(full_path):

raise ServerException("´{0}´ not found".format(self.path))

# path is a file
elif os.path.isfile(full_path):

self.handle_file(full_path)

# path is not a file
else:

raise ServerException("Unknown object ´{0}´".format(self.path))

except Exception as msg:

self.handle_error(msg)


def handle_file(self, full_path):

try:

with open(full_path, ´r´) as file:

content = file.read()


self.send_content(content,200)

except IOError as msg:

msg = "´{0}´ cannot be read: {1}".format(self.path, msg)

self.handle_error(msg)

Error_Page = """


Error accessing {path}


{msg}




"""

def handle_error(self, msg):


content = self.Error_Page.format(path= self.path,msg= msg)

self.send_content(content, 404)



def webserver(func):

httpAddress = (´´, 8080)

httpd = hs.HTTPServer(httpAddress, RequestHandler)

print ("I was server %s! %s" %(func,ctime()))

httpd.serve_forever()

t = threading.Thread(target=webserver,args=(u´webserver´,))


if __name__ == ´__main__´:
t.setDaemon(True)
t.start()

print ("all over %s" %ctime() )


#if __name__ == ´__main__´:



copyright©2018-2024 blender.gotopie.com