eventlet并发读写socket出现Second simultaneous问题
eventlet绿化和patch原理

实用工具状态机transitions

妙音 posted @ 2020年11月21日 09:42 in python with tags 状态机 , 969 阅读

说明

 
1. 状态机是一个非常实用的理论。在涉及到复杂的场景,建立状态机模型,能带来极大的方便。比如,网络连接、模型状态、业务逻辑。
 
2. 状态机并不复杂, 重要的是它的思想,能够极大减轻复杂度。使用时关键在于定义好事件和动作。
 
 

 基本概念

 
State: 状态
Event: 事件. 事件触发状态变换
Action: 动作. event发生前或后执行的动作
transition: 变换. 状态变换
 

github

 
https://github.com/pytransitions/transitions
 

安装

 
pip install transitions
 

简单示例

# 连接协议状态机
from transitions.extensions import HierarchicalMachine as Machine
from transitions.extensions.nesting import NestedState

class ConnectionStateMachine:
    """Connection state machine."""

    def __init__(self, callbacks=None):
        """
        :param callbacks: callbacks for the state machine
        """
        self.callbacks = {}

        # 定义状态
        self.states = ["STATE_NOT_CONNECTED",
                       {
                            'name': "STATE_CONNECTED",   # 状态名
                            'on_enter': self._on_enter_CONNECTED,  # 进入状态触发
                            'on_exit': self._on_exit_CONNECTED,    # 退出状态触发
                            'children': [     # 状态嵌套
                                "STATE_NOT_SELECTED",
                                {
                                    'name': "STATE_SELECTED",
                                    'on_enter': self._on_enter_CONNECTED_SELECTED
                                }
                            ]
                       }]

        # transition 1
        self.machine = Machine(model=self, states=self.states, initial="STATE_NOT_CONNECTED", auto_transitions=False)

        if callbacks:
            self.callbacks = callbacks

        # 定义状态变换
        self.machine.add_transition('connect', "STATE_NOT_CONNECTED", "STATE_CONNECTED_NOT_SELECTED")  # transition 2
        self.machine.add_transition('disconnect', "STATE_CONNECTED", "STATE_NOT_CONNECTED")  # transition 3
        self.machine.add_transition('select', "STATE_CONNECTED_NOT_SELECTED", "STATE_CONNECTED_SELECTED")  # transition 4
        self.machine.add_transition('deselect', "STATE_CONNECTED_SELECTED", "STATE_CONNECTED_NOT_SELECTED")  # transition 5
        self.machine.add_transition('timeoutT7', "STATE_CONNECTED_NOT_SELECTED", "STATE_NOT_CONNECTED")  # transition 6

    # 事件触发的动作
    def _on_enter_CONNECTED(self):
        if "on_enter_CONNECTED" in self.callbacks:
            self.callbacks["on_enter_CONNECTED"]()

    def _on_exit_CONNECTED(self):
        if "on_exit_CONNECTED" in self.callbacks:
            self.callbacks["on_exit_CONNECTED"]()

    def _on_enter_CONNECTED_SELECTED(self):
        if "on_enter_CONNECTED_SELECTED" in self.callbacks:
            self.callbacks["on_enter_CONNECTED_SELECTED"]()
 
 
 

定义状态机

 
# 一般都是两种:不嵌套、嵌套
from transitions import Machine   #不嵌套
from transitions.extensions import HierarchicalMachine as Machine # 嵌套

# 检查状态
machine.state
machine.is_<state_name>()
 

定义状态

# 状态可以是三种类型: 对象、字符串、字典
from transitions import State
states = [
    State(name="solid"),    # 对象
    "liquid",               # 字符串
    {"name": "gas"}         # 字典
]
 
 

定义变换

 
# 定义函数
machine.add_transition(trigger, source, dest, )
trigger(str)         方法名,触发状态转换
source(str or list)  源状态
dest(str)            目标状态

# 加上变换
machine.add_transition(trigger="wake_up", source="asleep", dest="hanging out")
machine.add_transition('work_out', 'hanging out', 'hungry')
machine.add_transition('nap', '*', 'asleep')   # 从任意状态变为asleep
 
 

 

Avatar_small
Diane Jones 说:
2020年12月02日 18:32

Find out Reliable and Legit Ways for Extra Income from Home. You are welcome to our scam free world of online earning. legit extra income from home

Avatar_small
Lagend SEO 说:
2020年12月07日 21:01

Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.. 123 movies

Avatar_small
Lagend SEO 说:
2020年12月10日 22:28

Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include. Konica Minolta WiFi router login password

Avatar_small
Ingríðr Carlu 说:
2020年12月13日 20:13

Punjab National Bank is an Ideal destination for all Banking need, and PNB offer a wide range of personal banking services including loans, credit cards, savings through Internet banking facility, where PNB Netbanking is an important part of the Digital Banking platform for today, and it allows customers to access their account from anywhere and anytime, and PNB net banking is quick and convenient which gives you the liberty of not having to visit the bank branch, and you can avoid those long queues in the branches while saving enormous time and energy. Rajasthan Pay Manager

Avatar_small
<a href="https://top 说:
2020年12月18日 01:11

What a wonderful article, great piece of information. <a href="https://topcoupons.co/xbox-vs-ps4-one-controller-battery-life/">ps4 controller battery life</a>

Avatar_small
LEGEND SEO 说:
2020年12月24日 15:50

Nice blog and absolutely outstanding. You can do something much better but i still say this perfect.Keep trying for the best. casino online canada

Avatar_small
Pak24tv 说:
2020年12月26日 13:15

I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept. Thank you for the post. types of government summary meaning 4 pillars of democracy

Avatar_small
Marjory Wyman 说:
2020年12月29日 15:52

WBCHSE 12th Model Paper 2021 is released by West Bengal Council of Higher Secondary Education in the pdf form. Students appearing for West Bengal 12th Exams 2021 must practice and analyze previous year’s WBCHSE HS question papers as it will help them to become familiar with the exam pattern, marking scheme and the different styles of question that are asked in the paper. While solving the question paper they must keep in mind timing should not exceed the exam time as it will help them in finishing the exam on time. As per the previous year dates probably the exam will be held in February/March 2021. WBCHSE HS 12th Model Paper 2021 WB HS Suggestion West Bengal Council of Higher Secondary School Education WBCHSE Established in the Year 1951. The Board and Headquarters of the Board are Located in Salt Lake City, Kolkata India. WB 12th Suggestion 2021

Avatar_small
Denise Carroll 说:
2020年12月31日 18:26

Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks anonse transwestytów

Avatar_small
Digital_Zone 说:
2021年1月13日 19:13

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. Airco Diest

Avatar_small
Digital_Zone 说:
2021年1月13日 19:22

Thanks for sharing the post.. parents are worlds best person in each lives of individual..they need or must succeed to sustain needs of the family. Lead generation

Avatar_small
Digital_Zone 说:
2021年1月13日 19:26

Thank you for some other informative blog. Where else could I get that type of information written in such an ideal means? I have a mission that I’m just now working on, and I have been at the look out for such information. Airco Bekkevoort

Avatar_small
Digital_Zone 说:
2021年1月13日 19:31

It is truly a well-researched content and excellent wording. I got so engaged in this material that I couldn’t wait reading. I am impressed with your work and skill. Thanks. Leads

Avatar_small
Digital_Zone 说:
2021年1月13日 19:35

I am unable to read articles online very often, but I’m glad I did today. This is very well written and your points are well-expressed. Please, don’t ever stop writing. Airco Herk-de-Stad

Avatar_small
Digital_Zone 说:
2021年1月13日 19:40

I am always looking for some free kinds of stuff over the internet. There are also some companies which give free samples. But after visiting your blog, I do not visit too many blogs. Thanks. Leadgeneratie

Avatar_small
Digital_Zone 说:
2021年1月13日 19:44

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. Airco Heusden-Zolder

Avatar_small
Digital_Zone 说:
2021年1月13日 19:49

Pretty good post. I have just stumbled upon your blog and enjoyed reading your blog posts very much. I am looking for new posts to get more precious info. Big thanks for the useful info. Ramen Leuven

Avatar_small
Digital_Zone 说:
2021年1月13日 21:45

I definitely enjoying every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep up the good work. Warmtepompen Limburg

Avatar_small
Digital_Zone 说:
2021年1月13日 22:48

Attractive, post. I just stumbled upon your weblog and wanted to say that I have liked browsing your blog posts. After all, I will surely subscribe to your feed, and I hope you will write again soon! Ramen en deuren Leuven

Avatar_small
Digital_Zone 说:
2021年1月13日 22:50

Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. Airco Leuven

Avatar_small
Digital_Zone 说:
2021年1月13日 22:51

I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have enjoyed reading. Leads

Avatar_small
Digital_Zone 说:
2021年1月13日 22:52

nice post, keep up with this interesting work. It really is good to know that this topic is being covered also on this web site so cheers for taking time to discuss this! Warmtepomp Hasselt

Avatar_small
Digital_Zone 说:
2021年1月13日 22:53

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. Thanks... PVC ramen Leuven

Avatar_small
Digital_Zone 说:
2021年1月13日 22:54

I can’t believe focusing long enough to research; much less write this kind of article. You’ve outdone yourself with this material without a doubt. It is one of the greatest contents. Airco Diepenbeek

Avatar_small
Digital_Zone 说:
2021年1月13日 22:55

Really a great addition. I have read this marvelous post. Thanks for sharing information about it. I really like that. Thanks so lot for your convene. Aluminium ramen Leuven

Avatar_small
Digital_Zone 说:
2021年1月13日 22:56

Someone Sometimes with visits your blog regularly and recommended it in my experience to read as well. The way of writing is excellent and also the content is top-notch. Thanks for that insight you provide the readers! Airco Lanaken

Avatar_small
Digital_Zone 说:
2021年1月13日 22:57

This type of message always inspiring and I prefer to read quality content, so happy to find good place to many here in the post, the writing is just great, thanks for the post. Leads genereren

Avatar_small
Digital_Zone 说:
2021年1月13日 22:58

If more people that write articles involved themselves with writing great content like you, more readers would be interested in their writings. I have learned too many things from your article. Airco Bilzen

Avatar_small
Digital_Zone 说:
2021年1月13日 22:59

You have performed a great job on this article. It’s very precise and highly qualitative. You have even managed to make it readable and easy to read. You have some real writing talent. Thank you so much. Leads kopen

Avatar_small
Digital_Zone 说:
2021年1月13日 23:00

Your blog has piqued a lot of real interest. I can see why since you have done such a good job of making it interesting. I appreciate your efforts very much. Ramen Leuven

Avatar_small
Digital_Zone 说:
2021年1月13日 23:01

I just couldn't leave your website before telling you that I truly enjoyed the top quality info you present to your visitors? Will be back again frequently to check up on new posts. SEO

Avatar_small
Digital_Zone 说:
2021年1月13日 23:02

Fabulous post, you have denoted out some fantastic points, I likewise think this s a very wonderful website. I will visit again for more quality contents and also, recommend this site to all. Thanks. Leadgeneration

Avatar_small
Digital_Zone 说:
2021年1月13日 23:03

I visit your blog regularly and recommend it to all of those who wanted to enhance their knowledge with ease. The style of writing is excellent and also the content is top-notch. Thanks for that shrewdness you provide the readers! Ramen en deuren Leuven

Avatar_small
Digital_Zone 说:
2021年1月13日 23:04

This article was written by a real thinking writer without a doubt. I agree many of the with the solid points made by the writer. I’ll be back day in and day for further new updates. SEO zoekmachine optimalisatie

Avatar_small
sk 说:
2021年1月29日 03:20

You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this... https://www.nutrielix.com/

Avatar_small
Denise Carroll 说:
2021年2月08日 01:58

Thanks for picking out the time to discuss this, I feel great about it and love studying more on this topic. It is extremely helpful for me. Thanks for such a valuable help again. PR článek cena

Avatar_small
Ladbrokes Review 说:
2021年3月02日 15:59

After reading Ladbrokes Review you will know that website is very unique in offering a great experience to all its customers from all parts of the world. The familiar Ladbrokes is a professional company which operates many high profile gambling websites around the world.

Avatar_small
Norton.com/setup 说:
2021年3月06日 14:13

<a href="https://sites.google.com/view/norton-com-setup-activation/norton-com-setup">Norton.com/setup</a>,If you have recently purchased a Norton Com Setup Product from an online store or a retail store.

Users can activate Roku from the official URL <a href="https://sites.google.com/view/url-roku-com-link">roku.com/link</a>

WWW Office.com/setup. You will get a complete Office Com Setup guide. You just need to follow our complete guideline regarding <a href="https://sites.google.com/view/www-office-com-setup-activate"> Office.com/setup</a>.

Avatar_small
james 说:
2021年3月16日 06:12

 purpose of the emergency essentials kits is to provide the highest priority, most critical survival gear in organized, modular kits to help you get home or get to the nearest help. The kits can be moved from one larger kit to another (i.e. transferring from your day pack to your backpacking pack or go-bag.) You want the essentials with you as often as possible. Evacuation checklist

Avatar_small
Denise Carroll 说:
2021年3月20日 18:58

Its a great pleasure reading your post.Its full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work. masaż grecki

Avatar_small
couponcodepromocode 说:
2021年3月20日 19:02

This website reminds me of another coupons website where <a href="http://couponcodepromocode.com/store/ar-face-mask/"> Ar Face Mask discount code </a> available. Using this coupons you can get up to 20% off on face masks.

Avatar_small
gg 说:
2021年3月20日 19:03

[url=google.com]google[/url]

Avatar_small
är Face Mask discoun 说:
2021年3月20日 19:03

This website reminds me of another coupons website where Ar Face Mask discount code available. Using this coupons you can get up to 20% off on face masks.

Avatar_small
james 说:
2021年3月22日 19:56

maintain our high level of Quality of Service, the team at Mecanica dedicates our passion to continuous self-improvement by keeping up with new and evolving technologies and methodologies within the field. Supporting Mecanica team members with continuing professional development and continuing education courses. As well as continuous research and publications of new and innovative documentation and analysis methodologies through the authoring and publication of peer reviewed technical papers. click for more info

Avatar_small
james 说:
2021年3月23日 19:25

Thanks for taking the time to discuss this, I feel strongly that love and read more on this topic. If possible, such as gain knowledge, would you mind updating your blog with additional information? It is very useful for me. https://bit.ly/38spwr

Avatar_small
james 说:
2021年3月25日 16:38

Awesome and interesting article. Great things you've always shared with us. Thanks. Just continue composing this kind of post. Personal assistant

Avatar_small
james 说:
2021年3月28日 01:21

99% Isopropyl Alcohol is also known as Isopropyl Alcohol Anhydrous is also known as 2-Hydroxy propane, 2-Hydroxypropane, Dimethyl carbinol, IPA, Isopropanol, Isopropyl Rubbing Alcohol, Isopropyl alcohol, Propan-2-ol, Propane, 2-hydroxy-, sec-Propanol, sec-Propyl Alcohol.A Isopropyl alcohol 99

Avatar_small
james 说:
2021年3月28日 05:55

Thanks for picking out the time to discuss this, I feel great about it and love studying more on this topic. It is extremely helpful for me. Thanks for such a valuable help again. CPA

Avatar_small
james 说:
2021年3月28日 14:37

Awesome and interesting article. Great things you've always shared with us. Thanks. Just continue composing this kind of post. ผลบอลวันนี้

Avatar_small
james 说:
2021年3月28日 19:24

I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work. พนันออนไลน์

Avatar_small
james 说:
2021年3月31日 15:01

reat content material as well as great layout. Your website deserves all of the positive feedback it’s been getting. I will be back soon for further quality contents. เว็บพนันออนไลน์

Avatar_small
james 说:
2021年4月01日 18:25

 

Output

I was reading some of your content on this website and I conceive this internet site is really informative ! Keep on putting up. voyance telephone
Avatar_small
james 说:
2021年4月05日 22:53

i am always looking for some free stuffs over the internet. there are also some companies which gives free samples. fire signs traits

Avatar_small
garage door repair D 说:
2021年4月07日 21:47

Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place..

Avatar_small
SMITHSEO 说:
2021年4月07日 22:37

Great article Lot's of information to Read...Great Man Keep Posting and update to People..Thanks research paper writing rules

Avatar_small
james 说:
2021年4月08日 21:55

i am always looking for some free stuffs over the internet. there are also some companies which gives free samples. dg casino

Avatar_small
james 说:
2021年4月09日 06:33

Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. 먹튀검증

Avatar_small
automatic gate repai 说:
2021年4月11日 00:26

Interesting post. I Have Been wondering about this issue, so thanks for posting. Pretty cool post.It 's really very nice and Useful post.Thanks

Avatar_small
best cashews online 说:
2021年5月31日 18:21

It truly is rather effective, while look at the truth as soon as the item extends to that concentrate on.

Avatar_small
buy youtube views hi 说:
2021年8月22日 00:58

I just couldn't leave your website before telling you that I truly enjoyed the top quality info you present to your visitors? Will be back again frequently to check up on new posts.

Avatar_small
NIMRA 说:
2021年9月03日 20:27

I'm glad I found this web site, I couldn't find any knowledge on this matter prior to.Also operate a site and if you are ever interested in doing some visitor writing for me if possible feel free to let me know, im always look for people to check out my web site. www.hostinglelo.in/ https://hostinglelo.in/

Avatar_small
dark web/deep web/d 说:
2022年8月07日 14:56

Carding or the "Rakhis" is a big thing going on in the Dark Web nowadays. This is where people from all corners of the World Wide Web to get connected to each other; and this is also where those shady deals and frauds happen too!  dark web links

Avatar_small
dark web/deep web/d 说:
2022年8月07日 15:34

This seems to be an effective method because it is able to pull up past crimes and provide other relevant information. But because it is still only a technique, more work needs to be done. deep web

Avatar_small
dark web/deep web/d 说:
2022年8月07日 16:01

Carding sites are not the only places that you need to worry about the dark. All kinds of shady people may want to get into your personal information and they may use the dark for their own purposes. dark web links

Avatar_small
dark web/deep web/d 说:
2022年8月07日 16:23

This tool works by locating the link on the CIDN part of the internet. With this, you'll get details such as the name of the website owner, his physical address, age, gender, and many more.  dark web sites

Avatar_small
dark web/deep web/d 说:
2022年8月07日 16:42

This can be determined by checking for the age of the website. The older the website is, the more likely it contains adult content. You may also use the search engines to look for adult content on the web. dark web

Avatar_small
dark web/deep web/d 说:
2022年8月07日 17:00

So, if you are curious about how to start affiliate marketing with ClickBank, all you need to do is take the first step. ClickBank is a great way to start making money online. work from home jobs

Avatar_small
dark web/deep web/d 说:
2022年8月07日 17:23

So you want to know how to be a successful ClickBank affiliate? There are many ways that can make you a bundle of cash, but you have to know what you are doing in order to succeed.  affiliate marketing success

Avatar_small
JKBOSE 12th Question 说:
2022年8月18日 13:00

JKBOSE 12th New Question Paper 2023, Jammu and Kashmir 12th Board exam performance as Pathway for all candidates to appear in the Board Exam. Board exams either 10th or 12th class exams are very important in a students life. JKBOSE 12th Question Paper 2023 12th class Board exams are mandatory for every student who is studying.

Avatar_small
skin 说:
2022年8月27日 05:05

Skin peels are used for Anti-ageing, skin rejuvenation, scarring, pigmentation, acne, blocked pores and oily skin .

Avatar_small
skin 说:
2022年9月08日 14:46

Skin peels are used for Anti-ageing, skin rejuvenation, scarring, pigmentation, acne, blocked pores and oily skin . Skin peels are also used for brightening and evening out skin tone and as a treatment for very fine lines.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter