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

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

大概业务流程图如下:

代码实现部分

1、C#代码

using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace IronPython调用示例
{
class Program
{
static void Main(string[] args)
{
string logPath = Path.Combine("logs", "log.txt");
if (File.Exists(logPath))
{
File.Delete(logPath);
}
FileStream fileStream = new FileStream(logPath, FileMode.OpenOrCreate);
//Console.WriteLine("------------------------以下是C#执行日志信息------------------------");
try
{
string pythonCodePath = Path.Combine("templates", "pythonCode.txt");
string sourceCodePath = Path.Combine("pys", "performer.py");
if (!File.Exists(pythonCodePath))
{
throw new Exception("Python模板不存在!");
}
if (!File.Exists(sourceCodePath))
{
throw new Exception("Python源代码文件不存在!");
}
string[] pythonCodeContent = File.ReadAllText(pythonCodePath).Split(new string[] { "\r\n" }, StringSplitOptions.None);
string[] sourceCodeContent = File.ReadAllText(sourceCodePath).Split(new string[] { "\r\n" }, StringSplitOptions.None);
if (sourceCodeContent == null || sourceCodeContent.Length == 0)
{
throw new Exception("Python代码不能为空!");
}
List<string> strList = new List<string>(pythonCodeContent);
foreach (var item in sourceCodeContent)
{
strList.Add(" " + item);
}
string codes = "";
foreach (var s in strList)
{
codes += s + Environment.NewLine;
}
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromString(codes);
ScriptScope scope = engine.CreateScope();
source.Execute(scope); dynamic performer = scope.GetVariable("performer");
dynamic per = performer("1005");
per.run();
var out_param = per.out_param;
Console.WriteLine(per.out_param);
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); Console.ReadKey();
}
finally
{
fileStream.Close();
fileStream.Dispose();
}
}
}
}

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

#.coding=utf-8

import db_manager

class performer():

    def __init__(self,in_param):
self.out_param = ''
self.in_param = in_param def run(self):

 3、节点脚本(performer.py)

import datetime
def get_now_time():
self.out_param = str(datetime.datetime.now())
def get_user_count():
order_id = self.in_param
sql = "select * from user_info where id = "+ order_id +""
querys = db_manager.sqlserver().execute_query(sql)
if(len(querys) >= 5):
self.out_param = '业务办理失败,此用户在全国范围内办理号码已经超过了5个!'
else:
self.out_param = '初审通过,已进入人工审核阶段!' get_now_time()
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. Java内部类类型

    可以在类中的任何位置定义内部类,并在其中编写Java语句.有三种类型的内部类. 内部类的类型取决于位置和声明的方式. 成员内部类 局部内部类 匿名内部类 成员内部类 成员内部类在类中声明的方式与声明成 ...

  2. leetcode.矩阵.240搜索二维矩阵II-Java

    1. 具体题目 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target.该矩阵具有以下特性:每行的元素从左到右升序排列:每列的元素从上到下升序排列. 示例: 现有矩阵 ...

  3. python获取港股通每日成交信息

    接口:ggt_daily 描述:获取港股通每日成交信息,数据从2014年开始 限量:单次最大1000,总量数据不限制 积分:用户积2000积分可调取,5000积分无限制,请自行提高积分,具体请参阅本文 ...

  4. Codeforces 490D Chocolate

    D. Chocolate time limit per test 1 second memory limit per test 256 megabytes input standard input o ...

  5. 原生js星星评分源码

    html: <div id="fiveStars"> <div>到场时间:<img v-for="(star,index) in stars ...

  6. Socket传输中文乱码

    最近在学习Socket的时候,遇到了中文乱码问题,在网上找到了一个说的很透彻的,这里分享一下:http://helloworlda.iteye.com/blog/1270703 现在问题是这样的: 打 ...

  7. LeetCode Array Easy 189. Rotate Array

    ---恢复内容开始--- Description Given an array, rotate the array to the right by k steps, where k is non-ne ...

  8. wdcp后台登陆访问失败处理方法

    用putty或xsheel链接 进入之后输入命令 service wdcp restart 之后显示ok就成功了

  9. Codeforces 19E&BZOJ 4424 Fairy(好题)

    日常自闭(菜鸡qaq).不过开心的是看了题解之后1A了.感觉这道题非常好,必须记录一下,一方面理清下思路,一方面感觉自己还没有完全领会到这道题的精髓先记下来以后回想. 题意:给定 n 个点,m 条边的 ...

  10. codeforces 1182E Product Oriented Recurrence 矩阵快速幂

    题意:设f(n) = c ^ (2n - 6) * f(n - 1) * f(n - 2) * f(n - 3), 问第n项是多少? 思路:官方题解:我们先转化一下,令g(x) =  c ^ x * ...