def main(): define("env", default="") # 配置文件 parse_command_line() if options.env == "apple": parse_config_file(os.path.join(os.path.dirname(__file__), "conf/apple_app.conf")) logging.info("use apple conf") else: logging.info("error: unknow conf") assert False my_app = Application() http_server = HTTPServer( my_app, idle_connection_timeout=options.idle_connection_timeout, xheaders=True ) # 加到erueka 注册中心 eureka_client.init_registry_client(eureka_server="http://192.168.2.64:8761/eureka/", app_name = "tornado-extensions", instance_port =int(options.port)) http_server.bind(int(options.port)) http_server.start() loop = asyncio.get_event_loop() # my_app.settings['mongo'] = mongodb.connect() my_app.settings['redis'] = loop.run_until_complete(redis.connect(loop, 7)) mysql_con_dict = dict() # mysql_con_dict["point_1"] = mysql.connect(options.mysql_doctor_db) # my_app.settings['mysql'] = mysql_con_dict loop.run_forever()
def register(self, service_name, service_addr, service_ttl, duration=30, service_port=0, management_port=8080, metadata={}): """ :param service_name: sample 'grpc-analysis-service-provider' :param service_addr: :param service_ttl: 心跳间隔 :param duration: 心跳超时 :param service_port: :param metadata: :return: """ instance_id = f'{service_name}:{service_addr}:{service_port}' metadata['gRPC.port'] = service_port # 兼容springcloud调用 eureka_client.init_registry_client( eureka_server=self._eureka_servers, app_name=service_name, instance_id=instance_id, instance_ip=service_addr, instance_port=management_port, status_page_url='actuator/info', # 兼容springcloud访问 health_check_url='actuator/health', renewal_interval_in_secs=service_ttl, duration_in_secs=duration, metadata=metadata)
def app_init(): port = int(os.environ.get('PORT', 5000)) service_name = os.environ.get('SERVICE_ALIAS', 'image-processor') eureka_server = os.environ.get('EUREKA_SERVER', 'http://localhost:8761/eureka') eureka_client.init_registry_client(eureka_server=eureka_server, app_name=service_name, instance_port=port)
def register_eureka(): # 配置Euraka 文档见: https://github.com/keijack/python-eureka-client/blob/master/README.zh_cn.md # 仅提供对外的服务即可 # The flowing code will register your server to eureka server and also start to send heartbeat every 30 seconds eureka_client.init_registry_client(eureka_server=EUREKA_SERVER_LIST, app_name="economic-model", instance_host=SERVER_HOST, instance_port=SERVER_PORT)
def register_service(eureka_server=None, instance_ip='127.0.0.1', instance_port='8000', app_name=None): # The flowing code will register your server to eureka server and also start to send heartbeat every 30 seconds eureka_client.init_registry_client(eureka_server=eureka_server, app_name=app_name, instance_port=instance_port, instance_ip=instance_ip)
def eureka_client_registration(self, application): if self.mock is False: eureka_client.init_registry_client( eureka_server="{}/eureka".format( os.environ["localEurekaServerURL"]), app_name=application.config['APP_NAME'], instance_port=application.config['PORT']) eureka_client.init_discovery_client("{}/eureka".format( os.environ["localEurekaServerURL"]))
def weatherEurekaService(): tornado.options.parse_command_line() log.info('开始向eureka服务器注册') # 注册eureka服务 eureka_client.init_registry_client(my_eureka_url, app_name, instance_port=8085) # API服务接口 log.info('创建服务controller接口') app = tornado.web.Application(handlers=[(r"/city/", WeatherHandle)]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
def register_service(eureka_server=None, instance_ip='127.0.0.1', instance_port='8000', app_name=None): """ 注册服务到eureka :param eureka_server: :param instance_ip: eureka host ip :param instance_port: eureka host port :param app_name: apollo app_id :return: None """ # The flowing code will register your server to eureka server and also start to send heartbeat every 30 seconds eureka_client.init_registry_client( eureka_server=eureka_server, app_name=app_name, instance_port=instance_port, instance_ip=instance_ip)
def main(): your_rest_server_port = 8000 eureka_client.init_registry_client(eureka_server="http://172.27.0.2:8761/eureka/", app_name="PERSON_SERVICE", instance_port=your_rest_server_port) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
def eurekaClient(): tornado.options.parse_command_line() eureka_client.init_registry_client(eureka_server=options.eurekaServer, app_name=options.appName, instance_port=options.port) app = tornado.web.Application( handlers=[(r"/info", Info), (r"/kmeans", IndexKMeans), (r"/naiveBayes", NaiveBayes), (r"/decisionTree", DecisionTree), (r"/createSvmModel", SvmTrain), (r"/svm", SvmTest), (r"/mgf", Mgf), (r"/multipleRegression", MultipleRegression), (r"/optimalSubset", OptimalSubset), (r"/rhythm", Rhythm), (r"/pca", Pca), (r"/createSvgImage", CreateSvgImage), (r"/tcc", tcc_svg)]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
import sys import time # The install method allows the easy installation of Python packages in realtime def install(package): subprocess.check_call([sys.executable, "-m", "pip", "install", package]) print("Project Nightowl v0.1") print("Video Stream Agent v0.1") print("initializing required python packages...") # Install Eureka Client to be used to connected to the Application Gateway install("py_eureka_client") import py_eureka_client.eureka_client as eureka_client # Setup the application gateway connection params your_rest_server_port = 8761 # The flowing code will register your server to eureka server and also start to send heartbeat every 30 seconds eureka_client.init_registry_client( eureka_server="http://YWRtaW4=:[email protected]:8761/eurka", app_name="video_stream_agent", instance_port=your_rest_server_port) # Conenct to HDFS print("Establishing connection to HDFS...") while True: print("Waiting for video stream.") time.sleep(60) # Delay for 1 minute (60 seconds).
import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import py_eureka_client.eureka_client as eureka_client from tornado.options import define, options define("port", default=3333, help="run on the given port", type=int) class IndexHandler(tornado.web.RequestHandler): def get(self): username = self.get_argument('username', 'Hello') self.write(username + ', Administrator User!') if __name__ == "__main__": #blog.csdn.net/moshowgame tornado.options.parse_command_line() #注册eureka服务 eureka_client.init_registry_client( eureka_server="http://10.64.140.34:8761/eureka/", app_name="python-tornado-xyweb", instance_port=3333) #获取eureka服务(有报错,先别用) #res = eureka_client.do_service("GRATEWAY", "/service/context/path") #print("result of other service" + res) app = tornado.web.Application(handlers=[(r"/", IndexHandler)]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
self.write(json.dumps({'result': np.bool(result)})) return self.write(json.dumps({'result': np.bool(False)})) class IndexHandler(tornado.web.RequestHandler): def get(self): self.finish("Tornado Swagger UI") handlers = [(r"/", IndexHandler), (r"/stamp/verify", VertifyStampHandler)] handlers.extend(swagger_handlers) def make_app(): return tornado.web.Application(handlers) if __name__ == "__main__": parse_command_line() eureka_client.init_registry_client( eureka_server= "http://localhost:50101/eureka/,http://localhost:50102/eureka/", app_name="python-stamp-server", instance_port=options.port, instance_ip="personnel-manage.top") app = make_app() app.listen(options.port) tornado.ioloop.IOLoop.instance().start()
# coding:utf-8 import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web, tornado.gen import py_eureka_client.eureka_client as eureka_client from tornado.options import define, options define("port", default=3333, help="run on the given port", type=int) class IndexHandler(tornado.web.RequestHandler): def get(self): username = self.get_argument('username', 'Hello') self.write(username + ', Administrator User1!') if __name__ == "__main__": tornado.options.parse_command_line() #注册eureka服务 eureka_server_list = "http://192.168.2.64:8761/eureka/" eureka_client.init_registry_client(eureka_server=eureka_server_list, app_name="python-tornado-xyweb", instance_port=3333) tornado.gen.sleep(2) app = tornado.web.Application(handlers=[(r"/info", IndexHandler)]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
os.environ['DJANGO_SETTINGS_MODULE'] = "djangowebscraperapp.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangowebscraperapp.settings") django.setup() # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ # [START staticurl] # STATIC_URL = '/static/' STATIC_URL = 'https://storage.googleapis.com/django-web-product-scraper/static/' # [END staticurl] STATIC_ROOT = 'static/' # import py_eureka_client.eureka_client as eureka_client # # # The flowing code will register your server to eureka server and also start to send heartbeat every 30 seconds # eureka_client.init_registry_client(eureka_server="http://169.254.130.117, http://discoveryserver:secretpassword@localhost:8080", # app_name="wepshopproductscraperapp", # instance_port=8080) import py_eureka_client.eureka_client as eureka_client gateway_server_port = 8761 # The flowing code will register your server to eureka server and also start to send heartbeat every 30 seconds eureka_client.init_registry_client( eureka_server="http://*****:*****@10.27.241.215:8761/eureka, http://discoveryserver:[email protected]:8761/eureka", app_name="django-web-product-scraper-microservice", instance_port=gateway_server_port)
# For Python 3.0 and later from urllib.request import urlopen except ImportError: # Fall back to Python 2's urllib2 from urllib2 import urlopen import json app = Flask(__name__) import py_eureka_client.eureka_client as eureka_client your_rest_server_port = 9090 # The flowing code will register your server to eureka server and also start to send heartbeat every 30 seconds eureka_client.init_registry_client( eureka_server="http://*****:*****@app.route('/user/stock/profile/<path:symbol>') def getCompanyProfileData(symbol): url = "https://financialmodelingprep.com/api/v3/company/profile/{}?apikey=5df07fe2e77eb907f2496af6f4a48260".format( symbol) response = urlopen(url) data = response.read().decode("utf-8") return json.loads(data) @app.route('/user/stock/quote/<path:symbol>') def getStockQuoteData(symbol):
import math import os from flask import Flask from flask import request import py_eureka_client.eureka_client as eureka_client from statistics import mean from model.EbsTitle import EbsTitle app = Flask(__name__) # app.config.from_object('yourapplication.default_settings') app.config.from_envvar("LIBINTEL_SETTINGS") your_rest_server_port = 5000 eureka_client.init_registry_client( eureka_server="http://*****:*****@app.route('/ebslists', methods=['POST']) def ebslist(): if not os.path.exists(location): os.makedirs(location) # reading parameters from HTTP-request ebs_filename = request.form['filename'] ebs_model = request.form['model'] ebs_mode = request.form['mode'] ebs_limit = float(request.form['limit'])
from flask import Flask, request, Response, jsonify import io from PIL import Image from darkflow.net.build import TFNet import cv2 import numpy as np from urllib.request import urlopen import py_eureka_client.eureka_client as eureka_client REST_SERVER_PORT = 5000 eureka_client.init_registry_client( eureka_server="http://localhost:8761/eureka", app_name="3102-YOLO-SERVICE", instance_port=REST_SERVER_PORT) print("Registered") options = { "model": "./cfg/yolo.cfg", "load": "./cfg/yolo.weights", "threshold": 0.1, "gpu": 1.0 } tfnet = TFNet(options) # Initialize the Flask application app = Flask(__name__) def image_to_byte_array(image: Image):
} ] #Syour_rest_server_port = 9090 # # The flowing code will register your server to eureka server and also start to send heartbeat every 30 seconds # eureka_client.init(eureka_server="http://your-eureka-server-peer1,http://your-eureka-server-peer2", # app_name="your_app_name", # instance_port=your_rest_server_port) # # The flowing code will register your server to eureka server and also start to send heartbeat every 30 seconds eureka_client.init_registry_client(eureka_server='http://*****:*****@app.route('/empdb/employee',methods=['GET']) def getAllEmp(): return jsonify({'emps':empDB}) @app.route('/empdb/employee/<empId>',methods=['GET']) def getEmp(empId): usr = [ emp for emp in empDB if (emp['id'] == empId) ] return jsonify({'emp':usr}) @app.route('/empdb/employee/<empId>',methods=['PUT']) def updateEmp(empId):
def register_eureka(config): return eureka_client.init_registry_client(eureka_server=config["hostname"], app_name=config["app_name"], instance_port=int( config["service_port"]))
def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'firmwareanalyze.settings') try: # print(Sys_code_err) # EUREKA接口 # 本地服务 # eureka_server_list = "http://localhost:10100/eureka/" # 远程服务 eureka_server_list = "http://172.16.60.5:10100/eureka/" # your_rest_server_host = "localhost" your_rest_server_host = "172.16.113.28" your_rest_server_port = 10112 # The flowing code will register your server to eureka server and also start to send heartbeat every 30 seconds # 注册服务 eureka_client.init_registry_client(eureka_server=eureka_server_list, app_name="firmware-analyze", instance_host=your_rest_server_host, instance_port=your_rest_server_port) # 发现服务 # you can reuse the eureka_server_list which you used in registry client listservice = eureka_client.init_discovery_client(eureka_server_list) # 调用服务 res = eureka_client.do_service( "SYSTEM-CODE", "/sys_code/run_status", # 返回类型,默认为 `string`,可以传入 `json`,如果传入值是 `json`,那么该方法会返回一个 `dict` 对象 return_type="string") print("result of other service" + res) syscode = eureka_client.do_service( "SYSTEM-CODE", "/sys_code/err_codes/all", # 返回类型,默认为 `string`,可以传入 `json`,如果传入值是 `json`,那么该方法会返回一个 `dict` 对象 return_type="json") # string_Sys_code_err = eureka_client.do_service("SYSTEM-CODE", "/sys_code/err_codes/all", # # 返回类型,默认为 `string`,可以传入 `json`,如果传入值是 `json`,那么该方法会返回一个 `dict` 对象 # return_type="string") settings.SYS_CODE = syscode['payload'] # print(type(settings.SYS_CODE)) # # syslog = eureka_client.do_service("SYSTEM-LOG", "/sys_log/add", # # 返回类型,默认为 `string`,可以传入 `json`,如果传入值是 `json`,那么该方法会返回一个 `dict` 对象 # return_type="string") # print("system-log:" + syslog) except ZeroDivisionError as e: print('except:', e) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?") from exc execute_from_command_line(sys.argv)
def run( self, service_name: Optional[str] = None, register: Optional[bool] = None, registrar_url: Optional[str] = None, ttl: Optional[int] = None, host_name: Optional[str] = None, # TODO: rename to port port_to_listen: Optional[int] = None, dta_type: Optional[DtaType] = None, is_ssl: Optional[bool] = None, consumers: Optional[List[Type[WorkConsumer]]] = None, ): """Class method which is used to invoke the server. """ properties = { "register": register, "service_name": service_name, "registrar_url": registrar_url, "ttl": ttl, "host_name": host_name, "port_to_listen": port_to_listen, "type": dta_type, "is_ssl": is_ssl, "consumers": consumers, } properties["name"] = properties.pop("service_name") properties["should_register"] = properties.pop("register") for name, value in properties.items(): if not value is None: setattr(self.config, name, value) if self.config.name == "UNKNOWN": log.warning( "no application name was specified instead using: UNKNOWN!") # register at eureka server if self.config.should_register: eureka_client.init_registry_client( eureka_server=self.config.registrar_url, instance_host=self.config.host_name, app_name=self.config.name, instance_port=int(self.config.port_to_listen), instance_secure_port_enabled=self.config.is_ssl, metadata={"dtaType": self.config.type.value}, ) assert (self.config.consumers ), "Have you called super() on your Server implemenation?" # start protocol consumer for protocol in self.config.consumers: instance: WorkConsumer = protocol(self._worker, self.config, self.options_type) instance.start() # fmt: off if __debug__: # use -O flag to remove all debug branches out of the bytecode print("") print(" +-------" + "-" * len(self.config.name) + "-------+") print( f" | {cr.Back.GREEN + cr.Fore.BLACK + self.config.name + cr.Back.RESET + cr.Fore.RESET} |" ) print(" +-------" + "-" * len(self.config.name) + "-------+") for setting in self.config.dict().items(): print(f" |- {setting[0]:<15} - {setting[1]}") print("") for consumer in self.config.consumers: print( f" [{consumer.__name__}] -> listening on port {self.config.port_to_listen}" ) print("") print(cr.Fore.YELLOW + " You see this message because __debug__ is true.") print(" Use the -O flag to enable optimization `python -O`." + cr.Fore.RESET) print("") # fmt: on try: while not self._should_stop.is_set(): self._should_stop.wait(0.5) except KeyboardInterrupt: sys.exit(0)