C#通过IronPython内嵌Python脚本,实现了对业务逻辑抽象及判断,适合在大量订单需要进行校验的场合使用。

比如,贷款时会对用户进行核查,核查过程可能存在多个节点,并且节点可能会随着政策而不断改变,每个节点就相当于一个脚本,通过脚本的出口关键字来确定流程分支走向。

大概业务流程图如下:

代码实现部分

1、C#代码

  1. using IronPython.Hosting;
  2. using Microsoft.Scripting;
  3. using Microsoft.Scripting.Hosting;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11.  
  12. namespace IronPython调用示例
  13. {
  14. class Program
  15. {
  16. static void Main(string[] args)
  17. {
  18. string logPath = Path.Combine("logs", "log.txt");
  19. if (File.Exists(logPath))
  20. {
  21. File.Delete(logPath);
  22. }
  23. FileStream fileStream = new FileStream(logPath, FileMode.OpenOrCreate);
  24. //Console.WriteLine("------------------------以下是C#执行日志信息------------------------");
  25. try
  26. {
  27. string pythonCodePath = Path.Combine("templates", "pythonCode.txt");
  28. string sourceCodePath = Path.Combine("pys", "performer.py");
  29. if (!File.Exists(pythonCodePath))
  30. {
  31. throw new Exception("Python模板不存在!");
  32. }
  33. if (!File.Exists(sourceCodePath))
  34. {
  35. throw new Exception("Python源代码文件不存在!");
  36. }
  37. string[] pythonCodeContent = File.ReadAllText(pythonCodePath).Split(new string[] { "\r\n" }, StringSplitOptions.None);
  38. string[] sourceCodeContent = File.ReadAllText(sourceCodePath).Split(new string[] { "\r\n" }, StringSplitOptions.None);
  39. if (sourceCodeContent == null || sourceCodeContent.Length == 0)
  40. {
  41. throw new Exception("Python代码不能为空!");
  42. }
  43. List<string> strList = new List<string>(pythonCodeContent);
  44. foreach (var item in sourceCodeContent)
  45. {
  46. strList.Add(" " + item);
  47. }
  48. string codes = "";
  49. foreach (var s in strList)
  50. {
  51. codes += s + Environment.NewLine;
  52. }
  53. ScriptEngine engine = Python.CreateEngine();
  54. ScriptSource source = engine.CreateScriptSourceFromString(codes);
  55. ScriptScope scope = engine.CreateScope();
  56. source.Execute(scope);
  57.  
  58. dynamic performer = scope.GetVariable("performer");
  59. dynamic per = performer("1005");
  60. per.run();
  61. var out_param = per.out_param;
  62. Console.WriteLine(per.out_param);
  63. Console.ReadKey();
  64. }
  65. catch (Exception ex)
  66. {
  67. Console.WriteLine(ex.Message);
  68.  
  69. Console.ReadKey();
  70. }
  71. finally
  72. {
  73. fileStream.Close();
  74. fileStream.Dispose();
  75. }
  76. }
  77. }
  78. }

 2、Python代码,模板(pythonCode.txt)

  1. #.coding=utf-8
  2.  
  3. import db_manager
  4.  
  5. class performer():
  6.  
  7. def __init__(self,in_param):
  8. self.out_param = ''
  9. self.in_param = in_param
  10.  
  11. def run(self):

 3、节点脚本(performer.py)

  1. import datetime
  2. def get_now_time():
  3. self.out_param = str(datetime.datetime.now())
  4. def get_user_count():
  5. order_id = self.in_param
  6. sql = "select * from user_info where id = "+ order_id +""
  7. querys = db_manager.sqlserver().execute_query(sql)
  8. if(len(querys) >= 5):
  9. self.out_param = '业务办理失败,此用户在全国范围内办理号码已经超过了5个!'
  10. else:
  11. self.out_param = '初审通过,已进入人工审核阶段!'
  12.  
  13. get_now_time()
  14. get_user_count()

  

  注意,此项目需要安装IronPython,并且把里面bin目录复制到我们C# debug目录下,项目源代码:https://github.com/lishuyiba/PythonPerformer

C#内嵌Python架构实现的更多相关文章

  1. Selenium2+python自动化26-js处理内嵌div滚动条

    前言 前面有篇专门用js解决了浏览器滚动条的问题,生活总是多姿多彩,有的滚动条就在页面上,这时候又得仰仗js大哥来解决啦. 一.内嵌滚动条 1.下面这张图就是内嵌div带有滚动条的样子,记住它的长相.

  2. python 内嵌函数, 闭包, 函数装饰器

    一.  函数内嵌 闭包 在python中,函数可以作为返回值, 可以给变量赋值. 在python中, 内置函数必须被显示的调用, 否则不会执行. #!/usr/bin/env python #-*- ...

  3. Python内嵌函数与Lambda表达式

    //2018.10.29 内嵌函数与lambda 表达式 1.如果在内嵌函数中需要改变全局变量的时候需要用到global语句对于变 量进行一定的说明与定义 2.内部的嵌套函数不可以直接在外部进行访问 ...

  4. 零基础入门学习Python(20)--函数:内嵌函数和闭包

    知识点 global关键字 使用global关键字,可以修改全局变量: >>> count = 5 >>> def Myfun(): count = 10 prin ...

  5. python 里内嵌函数是可以修改外部环境里的变量的

    python 里内嵌函数是可以修改外部环境里的变量的 关键是细节. 如果是简单变量类型, 那么不可以. 但是如果是容器类变量, 则没问题了. 代码如下: class G: pass def f(): ...

  6. Windows10内嵌Ubuntu子系统配置python开发环境

    Windows10内嵌Ubuntu子系统配置python开发环境 安装pycharm. 到intellij idea网站下载Linux环境下载免费的pycharm,通过ubuntu子系统内部的/mnt ...

  7. Selenium2+python自动化26-js处理内嵌div滚动条【转载】

    前言 前面有篇专门用js解决了浏览器滚动条的问题,生活总是多姿多彩,有的滚动条就在页面上,这时候又得仰仗js大哥来解决啦. 一.内嵌滚动条 1.下面这张图就是内嵌div带有滚动条的样子,记住它的长相.

  8. (十九)python 3 内嵌函数和闭包

    内嵌函数:函数里又嵌套一个函数 def fun1(): print('fun1()在被调用') def fun2(): print('fun2()在被调用') fun2() 闭包: 闭包是函数里面嵌套 ...

  9. selenium3 + python - js 内嵌滚动处理

    一.js内嵌html <!DOCTYPE html><html lang="en"><head> <meta charset=" ...

随机推荐

  1. CentOS系统更换软件安装源yum

    第一步:备份你的原镜像文件,以免出错后可以恢复. mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.back ...

  2. windows配置环境变量

    windows配置环境变量 1.第一步 2.第二步 3.第三步

  3. 第一周复习二 (CSS样式表及其属性)

    样式表三种写法 1内联写法:style直接写在标签内.个人感觉多用于个别标签,一般情况优先级较高 style="font-size:16px;" 2内嵌写法:写在<head& ...

  4. mongo聚合命令

    db.getCollection('chat').aggregate([ { "$match": { "last": 1, "type": ...

  5. MySQL-技术专区-数据库权限管理

    前言 学习mysql数据库,对于它的权限的管理是关键的一环.所以,下面介绍的是MySQL权限的管理. MySQL权限表 MySQL数据库实际上是通过将用户写入mysql库中对应的权限表来控制访问权限的 ...

  6. ASP.NET MVC 学习笔记之TempData、HttpContext和HttpContextBase杂谈

    TempData本质上是Session 但是有一点不同的是,TempData被赋值之后,一旦被Action访问一次之后,马上就会清空. System.Web.HttpContext 和System.W ...

  7. Cobalt Strike特征修改

    一.Teamserver模块端口信息 vim teamserver修改Cobalt Strike默认服务端50500端口为其他任意端口 二.SSL默认证书信息 Cobalt Strike默认SSL证书 ...

  8. git 分支相关操作

    git status  查看当前工作区 会显示分支 如下 D:\工程\vue_study\testplat_vue>git statusOn branch masternothing to co ...

  9. koa 中间件 koa-art-template 的使用

    例子 const Koa = require('koa'); const render =require('koa-art-template'); const path= require('path' ...

  10. Rikka with Competition

    Rikka with Competition 给出一个大小为n的集合\(\{a_i\}\),每次从集合中随机挑出一对数\(a_i,a_j\),如果\(|a_i-a_j|>K\),那么从集合中删掉 ...