├── CHANGES ├── LICENSE ├── README.rst ├── bootstrap.py ├── buildout.cfg ├── docs └── index.rst ├── eventsource ├── __init__.py ├── client.py ├── listener.py └── request.py └── setup.py /CHANGES: -------------------------------------------------------------------------------- 1 | version 1.1.0: 2 | * syntax clean up 3 | * in listener: 4 | * removed events buffering as a deque 5 | * added toro dependency 6 | * added toro.asyncresult to replace event's deque buffer 7 | * used toro.asyncresult to block and call the event loop 8 | * in client: 9 | * added keep alive parameter 10 | 11 | version 1.0.5: 12 | * moved event_loop callback rearming away 13 | * changed events buffer from list to deque 14 | 15 | version 1.0.4: 16 | * added invalid SSL certificates support 17 | * integrated patches from Ian Whyman: 18 | * support of bad HTTP services implementations (be compatible with '\n' and '\r\n') 19 | * added user/password support for connections in client 20 | * integrated patches from Коренберг Марк: 21 | * use of json module of tornado 22 | * cosmetic changes 23 | 24 | version 1.0.3: 25 | * added support for SSL connections 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright © 2007 Free Software Foundation, Inc. 5 | 6 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | The GNU General Public License is a free, copyleft license for software and other kinds of works. 10 | 11 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 12 | 13 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. 14 | 15 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. 16 | 17 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 18 | 19 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. 20 | 21 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. 22 | 23 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. 24 | 25 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 26 | 27 | The precise terms and conditions for copying, distribution and modification follow. 28 | 29 | TERMS AND CONDITIONS 30 | 31 | 0. Definitions. 32 | 33 | "This License" refers to version 3 of the GNU General Public License. 34 | 35 | "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. 36 | 37 | "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. 38 | 39 | To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. 40 | 41 | A "covered work" means either the unmodified Program or a work based on the Program. 42 | 43 | To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. 44 | 45 | To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. 46 | 47 | An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 48 | 49 | 1. Source Code. 50 | The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. 51 | 52 | A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. 53 | 54 | The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. 55 | 56 | The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. 57 | 58 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. 59 | 60 | The Corresponding Source for a work in source code form is that same work. 61 | 62 | 2. Basic Permissions. 63 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. 64 | 65 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. 66 | 67 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 68 | 69 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 70 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. 71 | 72 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 73 | 74 | 4. Conveying Verbatim Copies. 75 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. 76 | 77 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 78 | 79 | 5. Conveying Modified Source Versions. 80 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: 81 | 82 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 83 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". 84 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. 85 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. 86 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 87 | 88 | 6. Conveying Non-Source Forms. 89 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: 90 | 91 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. 92 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. 93 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. 94 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. 95 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. 96 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. 97 | 98 | A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. 99 | 100 | "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. 101 | 102 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). 103 | 104 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. 105 | 106 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 107 | 108 | 7. Additional Terms. 109 | "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. 110 | 111 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. 112 | 113 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: 114 | 115 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 116 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or 117 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or 118 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or 119 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 120 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. 121 | All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. 122 | 123 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. 124 | 125 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 126 | 127 | 8. Termination. 128 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). 129 | 130 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. 131 | 132 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. 133 | 134 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 135 | 136 | 9. Acceptance Not Required for Having Copies. 137 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 138 | 139 | 10. Automatic Licensing of Downstream Recipients. 140 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. 141 | 142 | An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. 143 | 144 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 145 | 146 | 11. Patents. 147 | A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". 148 | 149 | A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. 150 | 151 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. 152 | 153 | In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. 154 | 155 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. 156 | 157 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. 158 | 159 | A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. 160 | 161 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 162 | 163 | 12. No Surrender of Others' Freedom. 164 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 165 | 166 | 13. Use with the GNU Affero General Public License. 167 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 168 | 169 | 14. Revised Versions of this License. 170 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 171 | 172 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. 173 | 174 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. 175 | 176 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 177 | 178 | 15. Disclaimer of Warranty. 179 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 180 | 181 | 16. Limitation of Liability. 182 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 183 | 184 | 17. Interpretation of Sections 15 and 16. 185 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 186 | 187 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | README: Event Source Library for Python 2 | ======================================= 3 | 4 | This library implements W3C Draft's on event-source: 5 | 6 | * http://dev.w3.org/html5/eventsource/ 7 | 8 | It enables a halfduplex communication from server to client, but initiated 9 | by the client, through standard HTTP(S) communication. 10 | 11 | Dependances 12 | ----------- 13 | 14 | * Fairly recent python (tested with 2.7) 15 | * Fairly recent tornado (tested with 2.2.1) 16 | 17 | Usage 18 | ----- 19 | 20 | 1. Launch the server:: 21 | 22 | eventsource-server -P 8888 -i -k 50000 23 | 24 | 2. Launch the client:: 25 | 26 | eventsource-client 42:42:42:42:42:42 -r 5000 -P 8888 27 | 28 | 3. Send requests:: 29 | 30 | eventsource-request 42:42:42:42:42:42 ping "42" 31 | eventsource-request 42:42:42:42:42:42 close 32 | 33 | Command Line arguments 34 | ---------------------- 35 | 36 | * `eventsource/listener.py` or `eventsource-server`:: 37 | 38 | usage: eventsource/listener.py [-h] [-H HOST] [-P PORT] [-d] 39 | [-j] [-k KEEPALIVE] [-i] 40 | 41 | Event Source Listener 42 | 43 | optional arguments: 44 | -h, --help show this help message and exit 45 | -H HOST, --host HOST Host to bind on 46 | -P PORT, --port PORT Port to bind on 47 | -d, --debug enables debug output 48 | -j, --json to enable JSON Event 49 | -k KEEPALIVE, --keepalive KEEPALIVE 50 | Keepalive timeout, in milliseconds 51 | -i, --id to generate identifiers 52 | 53 | * `eventsource/client.py` or `eventsource-client`:: 54 | 55 | usage: eventsource/client.py [-h] [-H HOST] [-P PORT] [-d] 56 | [-r RETRY] 57 | token 58 | 59 | Event Source Client 60 | 61 | positional arguments: 62 | token Token to be used for connection 63 | 64 | optional arguments: 65 | -h, --help show this help message and exit 66 | -H HOST, --host HOST Host to connect to 67 | -P PORT, --port PORT Port to be used connection 68 | -d, --debug enables debug output 69 | -r RETRY, --retry RETRY 70 | Reconnection timeout 71 | 72 | * `eventsource/send_request.py` or `eventsource-request`:: 73 | 74 | usage: eventsource/send_request.py [-h] [-H HOST] [-P PORT] [-j] 75 | token action [data] 76 | 77 | Generates event for Event Source Library 78 | 79 | positional arguments: 80 | token Token to be used for connection 81 | action Action to send 82 | data Data to be sent 83 | 84 | optional arguments: 85 | -h, --help show this help message and exit 86 | -H HOST, --host HOST Host to connect to 87 | -P PORT, --port PORT Port to be used connection 88 | -j, --json Treat data as JSON 89 | 90 | Install 91 | ------- 92 | 93 | You can install it by getting it from pypi:: 94 | 95 | pip install event-source-library 96 | 97 | or by getting this repository and install it manually:: 98 | 99 | python setup.py install 100 | 101 | Development 102 | ----------- 103 | 104 | To develop, you can use buildout:: 105 | 106 | pip install zc.buildout # if you haven't got it 107 | buildout 108 | ls bin/ 109 | 110 | Or you can do: 111 | 112 | python setup.py develop 113 | 114 | which will deploy the commands globally like an install, but still linked to 115 | the current sources. 116 | 117 | Integrate 118 | --------- 119 | 120 | On the server side, basically all you have to do is to add the following to your code:: 121 | 122 | from eventsource import listener 123 | 124 | application = tornado.web.Application([ 125 | (r"/(.*)/(.*)", listener.EventSourceHandler, 126 | dict(event_class=EVENT, 127 | keepalive=KEEPALIVE)), 128 | ]) 129 | 130 | application.listen(PORT) 131 | tornado.ioloop.IOLoop.instance().start() 132 | 133 | where: 134 | 135 | * ``PORT`` is an integer for the port to bind to 136 | 137 | * ``KEEPALIVE`` is an integer for the timeout between two keepalive messages (to protect from disconnections), in milliseconds 138 | 139 | * ``EVENT`` is a eventsource.listener.Event based class, either one you made or 140 | 141 | * ``eventsource.listener.StringEvent`` : Each event gets and resends multiline strings 142 | 143 | * ``eventsource.listener.StringIdEvent`` : Each event gets and resends multiline strings, with an unique id for each event 144 | 145 | * ``eventsource.listener.JSONEvent`` : Each event gets and resends JSON valid strings 146 | 147 | * ``eventsource.listener.JSONIdEvent`` : Each event gets and resends JSON valid string, with an unique id for each event 148 | 149 | See http://www.tornadoweb.org/en/stable/web.html#application-configuration for more details. 150 | 151 | Extend 152 | ------ 153 | 154 | To extend the behaviour of the event source library, without breaking eventsource 155 | definition, the Event based classes implements all processing elements that shall 156 | be done on events. 157 | 158 | There is two abstract classes that defines Event: 159 | * ``eventsource.listener.Event`` : defines the constructor of an Event 160 | * ``eventsource.listener.EventId`` : defines an always incrementing id handler 161 | 162 | here is an example to create a new Event that takes multiline data and join it in a one 163 | line string seperated with semi-colons. 164 | 165 | :: 166 | 167 | class OneLineEvent(Event): 168 | ACTIONS = ["ping",Event.FINISH] 169 | 170 | """Property to enable multiline output of the value""" 171 | def get_value(self): 172 | # replace carriage returns by semi-colons 173 | # this method shall always return a list (even if one value) 174 | return [";".join([line for line in self._value.split('\n')])] 175 | 176 | value = property(get_value,set_value) 177 | 178 | And now, I want to add basic id support to OneLineEvent, in OneLineEventId, 179 | nothing is easier :: 180 | 181 | class OneLineEventId(OneLineEvent,EventId): 182 | id = property(EventId.get_value) 183 | 184 | Or if I want the id to be a timestamp:: 185 | 186 | import time 187 | class OneLineTimeStampEvent(OneLineEvent): 188 | id = property(lambda s: "%f" % (time.time(),)) 189 | 190 | You can change the behaviour of a few things in a Event-based class: 191 | 192 | * ``Event.LISTEN`` contains the ``GET`` action to open a connection (per default "poll") 193 | * ``Event.FINISH`` contains the ``POST`` action to close a connection (per default "close") 194 | * ``Event.RETRY`` contains the ``POST`` action to define the timeout after reconnecting on network disconnection (per default "0", which means disabled) 195 | * in the ``Event.ACTIONS`` list, you define what POST actions are allowed, per default, only Event.FINISH is allowed. 196 | * ``Event.content_type`` contains the "content_type" that will be asked for every form (it is not enforced). 197 | 198 | To change the way events are generated, you can directly call ``EventSourceHandler.buffer_event()`` 199 | to create a new event to be sent. But the post action is best, at least while WSGI can't handle 200 | correctly long polling connections. 201 | 202 | Licensing 203 | --------- 204 | 205 | :: 206 | 207 | Python Event Source Library 208 | 209 | (c) 2012 Bernard Pratz 210 | Patches by Ian Whyman, Коренберг Марк and Max Suraev 211 | 212 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. 213 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 214 | You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. 215 | 216 | EOF 217 | -------------------------------------------------------------------------------- /bootstrap.py: -------------------------------------------------------------------------------- 1 | ############################################################################## 2 | # 3 | # Copyright (c) 2006 Zope Foundation and Contributors. 4 | # All Rights Reserved. 5 | # 6 | # This software is subject to the provisions of the Zope Public License, 7 | # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. 8 | # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED 9 | # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 10 | # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS 11 | # FOR A PARTICULAR PURPOSE. 12 | # 13 | ############################################################################## 14 | """Bootstrap a buildout-based project 15 | 16 | Simply run this script in a directory containing a buildout.cfg. 17 | The script accepts buildout command-line options, so you can 18 | use the -c option to specify an alternate configuration file. 19 | """ 20 | 21 | import os, shutil, sys, tempfile 22 | from optparse import OptionParser 23 | 24 | tmpeggs = tempfile.mkdtemp() 25 | 26 | usage = '''\ 27 | [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] 28 | 29 | Bootstraps a buildout-based project. 30 | 31 | Simply run this script in a directory containing a buildout.cfg, using the 32 | Python that you want bin/buildout to use. 33 | 34 | Note that by using --setup-source and --download-base to point to 35 | local resources, you can keep this script from going over the network. 36 | ''' 37 | 38 | parser = OptionParser(usage=usage) 39 | parser.add_option("-v", "--version", help="use a specific zc.buildout version") 40 | 41 | parser.add_option("-t", "--accept-buildout-test-releases", 42 | dest='accept_buildout_test_releases', 43 | action="store_true", default=False, 44 | help=("Normally, if you do not specify a --version, the " 45 | "bootstrap script and buildout gets the newest " 46 | "*final* versions of zc.buildout and its recipes and " 47 | "extensions for you. If you use this flag, " 48 | "bootstrap and buildout will get the newest releases " 49 | "even if they are alphas or betas.")) 50 | parser.add_option("-c", "--config-file", 51 | help=("Specify the path to the buildout configuration " 52 | "file to be used.")) 53 | parser.add_option("-f", "--find-links", 54 | help=("Specify a URL to search for buildout releases")) 55 | 56 | 57 | options, args = parser.parse_args() 58 | 59 | ###################################################################### 60 | # load/install distribute 61 | 62 | to_reload = False 63 | try: 64 | import pkg_resources, setuptools 65 | if not hasattr(pkg_resources, '_distribute'): 66 | to_reload = True 67 | raise ImportError 68 | except ImportError: 69 | ez = {} 70 | 71 | try: 72 | from urllib.request import urlopen 73 | except ImportError: 74 | from urllib2 import urlopen 75 | 76 | exec(urlopen('http://python-distribute.org/distribute_setup.py').read(), ez) 77 | setup_args = dict(to_dir=tmpeggs, download_delay=0, no_fake=True) 78 | ez['use_setuptools'](**setup_args) 79 | 80 | if to_reload: 81 | reload(pkg_resources) 82 | import pkg_resources 83 | # This does not (always?) update the default working set. We will 84 | # do it. 85 | for path in sys.path: 86 | if path not in pkg_resources.working_set.entries: 87 | pkg_resources.working_set.add_entry(path) 88 | 89 | ###################################################################### 90 | # Install buildout 91 | 92 | ws = pkg_resources.working_set 93 | 94 | cmd = [sys.executable, '-c', 95 | 'from setuptools.command.easy_install import main; main()', 96 | '-mZqNxd', tmpeggs] 97 | 98 | find_links = os.environ.get( 99 | 'bootstrap-testing-find-links', 100 | options.find_links or 101 | ('http://downloads.buildout.org/' 102 | if options.accept_buildout_test_releases else None) 103 | ) 104 | if find_links: 105 | cmd.extend(['-f', find_links]) 106 | 107 | distribute_path = ws.find( 108 | pkg_resources.Requirement.parse('distribute')).location 109 | 110 | requirement = 'zc.buildout' 111 | version = options.version 112 | if version is None and not options.accept_buildout_test_releases: 113 | # Figure out the most recent final version of zc.buildout. 114 | import setuptools.package_index 115 | _final_parts = '*final-', '*final' 116 | def _final_version(parsed_version): 117 | for part in parsed_version: 118 | if (part[:1] == '*') and (part not in _final_parts): 119 | return False 120 | return True 121 | index = setuptools.package_index.PackageIndex( 122 | search_path=[distribute_path]) 123 | if find_links: 124 | index.add_find_links((find_links,)) 125 | req = pkg_resources.Requirement.parse(requirement) 126 | if index.obtain(req) is not None: 127 | best = [] 128 | bestv = None 129 | for dist in index[req.project_name]: 130 | distv = dist.parsed_version 131 | if _final_version(distv): 132 | if bestv is None or distv > bestv: 133 | best = [dist] 134 | bestv = distv 135 | elif distv == bestv: 136 | best.append(dist) 137 | if best: 138 | best.sort() 139 | version = best[-1].version 140 | if version: 141 | requirement = '=='.join((requirement, version)) 142 | cmd.append(requirement) 143 | 144 | import subprocess 145 | if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=distribute_path)) != 0: 146 | raise Exception( 147 | "Failed to execute command:\n%s", 148 | repr(cmd)[1:-1]) 149 | 150 | ###################################################################### 151 | # Import and run buildout 152 | 153 | ws.add_entry(tmpeggs) 154 | ws.require(requirement) 155 | import zc.buildout.buildout 156 | 157 | if not [a for a in args if '=' not in a]: 158 | args.append('bootstrap') 159 | 160 | # if -c was provided, we push it back into args for buildout' main function 161 | if options.config_file is not None: 162 | args[0:0] = ['-c', options.config_file] 163 | 164 | zc.buildout.buildout.main(args) 165 | shutil.rmtree(tmpeggs) 166 | -------------------------------------------------------------------------------- /buildout.cfg: -------------------------------------------------------------------------------- 1 | [buildout] 2 | newest = false 3 | parts = eggs 4 | develop = . 5 | eggs-directory = var/eggs 6 | develop-eggs-directory = var/develop-eggs 7 | parts-directory = var/parts 8 | bin-directory = bin 9 | 10 | [eggs] 11 | recipe = zc.recipe.egg 12 | eggs = 13 | eventsource 14 | tornado>=4.4 15 | nose 16 | Sphinx 17 | Sphinx-PyPI-upload 18 | interpreter = python 19 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. Event Source Library documentation master file, created by 2 | sphinx-quickstart on Sat May 26 21:21:51 2012. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Eventsource library for python 7 | ============================== 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | 12 | this library installs also three utilities: 13 | - **eventsource-server** : that helps to create an eventsource server (module `eventsource.listener`) 14 | - **eventsource-client** : that helps to create an eventsource client (module `eventsource.client`) 15 | - **eventsource-request** : that helps to send requests to the client through the server (module `eventsource.request`) 16 | see `--help` or README for more information 17 | 18 | Have a look at the README part of this documentation to integrate or extend this library. 19 | 20 | eventsource Package 21 | =================== 22 | 23 | This library exposes three modules, two of them based on tornado library. The listener module, ran 24 | by the server, waits for incoming connections. When a client, running the client module, connects 25 | to the listener, it waits for incoming events from the server. And finally, when the request module 26 | is ran, it posts events on the server, who forwards them to the client. 27 | 28 | The request module relies only on `urllib2`. 29 | 30 | :mod:`listener` Module 31 | ---------------------- 32 | 33 | This module opens a new long polling connection on a listener, and waits for events to come. 34 | 35 | .. automodule:: eventsource.listener 36 | :members: 37 | 38 | :mod:`client` Module 39 | -------------------- 40 | 41 | This module listens for incoming connections and forwards events from "request" to "client" 42 | using tornado http long-polling on the client side, and http post on the request side. 43 | 44 | .. automodule:: eventsource.client 45 | :members: 46 | :undoc-members: 47 | 48 | :mod:`request` Module 49 | --------------------- 50 | 51 | This module only connects to listener's rest POST interface to send new events 52 | 53 | .. automodule:: eventsource.request 54 | :members: 55 | :undoc-members: 56 | 57 | .. include:: ../README.rst 58 | 59 | Resources 60 | ========= 61 | 62 | - http://stackoverflow.com/questions/10665569/websocket-event-source-implementation-to-expose-a-two-way-rpc-to-a-python-dj 63 | - http://stackoverflow.com/questions/8812715/using-a-simple-python-generator-as-a-co-routine-in-a-tornado-async-handler 64 | - http://dev.w3.org/html5/eventsource/ 65 | - http://github.com/guyzmo/event-source-library/ 66 | - http://www.tornadoweb.org/ 67 | 68 | 69 | Indices and tables 70 | ================== 71 | 72 | * :ref:`genindex` 73 | * :ref:`modindex` 74 | * :ref:`search` 75 | 76 | -------------------------------------------------------------------------------- /eventsource/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | -------------------------------------------------------------------------------- /eventsource/client.py: -------------------------------------------------------------------------------- 1 | # -+- encoding: utf-8 -+- 2 | """ 3 | .. module:: listener 4 | :platform: Unix 5 | :synopsis: This module provides an eventsource client based on tornado 6 | 7 | .. moduleauthor:: Bernard Pratz 8 | .. moduleauthor:: Ian Whyman 9 | .. moduleauthor:: Коренберг Марк 10 | 11 | """ 12 | import sys 13 | import time 14 | import argparse 15 | import logging 16 | log = logging.getLogger("eventsource.client") 17 | 18 | from tornado.ioloop import IOLoop 19 | from tornado.httpclient import AsyncHTTPClient, HTTPRequest 20 | 21 | class Event(object): 22 | """ 23 | Contains a received event to be processed 24 | """ 25 | def __init__(self): 26 | self.name = None 27 | self.data = None 28 | self.id = None 29 | 30 | def __repr__(self): 31 | return "Event<%s,%s,%s>" % (str(self.id), str(self.name), str(self.data.replace("\n","\\n"))) 32 | 33 | class EventSourceClient(object): 34 | """ 35 | This module opens a new connection to an eventsource server, and wait for events. 36 | """ 37 | def __init__(self, url, action, target, callback = None, retry = 0, keep_alive = False, ssl = False, validate_cert = False, user = None, password = None): 38 | """ 39 | Build the event source client 40 | :param url: string, the url to connect to 41 | :param action: string of the listening action to connect to 42 | :param target: string with the listening token 43 | :param callback: function with one parameter (Event) that gets called for each received event 44 | :param retry: timeout between two reconnections (0 means no reconnection) 45 | """ 46 | log.debug("EventSourceClient(%s,%s,%s,%s,%s)" % (url, action, target, callback, retry)) 47 | 48 | self.data_partial = None 49 | self.last_event_id = None 50 | self.retry_timeout = int(retry) 51 | self.keep_alive = keep_alive 52 | self._url = "%s://%s/%s/%s" % ("https" if ssl else "http", url, action, target) 53 | self._headers = {"Accept": "text/event-stream"} 54 | self._user = user 55 | self._password = password 56 | 57 | AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient") 58 | self.http_client = AsyncHTTPClient() 59 | self.http_request = HTTPRequest(url = self._url, 60 | method="GET", 61 | headers={"content-type":"text/event-stream"}, 62 | request_timeout = 0, 63 | validate_cert = validate_cert, 64 | streaming_callback = self.handle_stream, 65 | auth_username = user, 66 | auth_password = password) 67 | if callback is None: 68 | self.cb = lambda e: log.info( "received %s" % (e,) ) 69 | else: 70 | self.cb = callback 71 | 72 | def _get_headers(self): 73 | """ 74 | Provide headers to be used for next request. By default checks for 75 | self.last_event_id and populates a header as needed. 76 | """ 77 | if self.last_event_id: 78 | self._headers["Last-Event-ID"] = self.last_event_id 79 | return self._headers 80 | 81 | def _get_request(self): 82 | """ 83 | Return a suitablty initialized HTTPRequest 84 | """ 85 | return HTTPRequest(url = self._url, 86 | method="GET", 87 | headers = self._get_headers(), 88 | request_timeout = 0, 89 | streaming_callback = self.handle_stream, 90 | auth_username = self._user, 91 | auth_password = self._password) 92 | 93 | def poll(self): 94 | """ 95 | Function to call to start listening 96 | """ 97 | log.debug("poll()") 98 | 99 | while True: 100 | self.http_client.fetch(self._get_request(), self.handle_request) 101 | IOLoop.instance().start() 102 | if self.retry_timeout == -1: 103 | break 104 | time.sleep(self.retry_timeout/1000) 105 | 106 | def end(self): 107 | """ 108 | Function to call to end listening 109 | """ 110 | log.debug("end()") 111 | 112 | self.retry_timeout=-1 113 | IOLoop.instance().stop() 114 | 115 | def handle_stream(self, message): 116 | """ 117 | Acts on message reception 118 | :param message: string of an incoming message 119 | 120 | parse all the fields and builds an Event object that is passed to the callback function 121 | """ 122 | log.debug("handle_stream(...)") 123 | 124 | if not message.endswith("\n"): 125 | log.debug("got partial chunk") 126 | if self.data_partial: 127 | self.data_partial += message 128 | else: 129 | self.data_partial = message 130 | return 131 | 132 | if self.data_partial: 133 | log.debug("rebuiling chunked response") 134 | message = self.data_partial + message 135 | self.data_partial = None 136 | 137 | event = Event() 138 | for line in message.strip().splitlines(): 139 | (field, value) = line.split(":", 1) 140 | field = field.strip() 141 | 142 | if field == "event": 143 | event.name = value.lstrip() 144 | elif field == "data": 145 | value = value.lstrip() 146 | if event.data is None: 147 | event.data = value 148 | else: 149 | event.data = "%s\n%s" % (event.data, value) 150 | elif field == "id": 151 | event.id = value.lstrip() 152 | self.last_event_id = event.id 153 | elif field == "retry": 154 | try: 155 | self.retry_timeout = int(value) 156 | log.info( "timeout reset: %s" % (value,) ) 157 | except ValueError: 158 | pass 159 | elif field == "": 160 | log.debug( "received comment: %s" % (value,) ) 161 | else: 162 | raise Exception("Unknown field !") 163 | if event.name is not None: 164 | self.cb(event) 165 | 166 | 167 | def handle_request(self, response): 168 | """ 169 | Function that gets called on non long-polling actions, 170 | on error or on end of polling. 171 | 172 | :param response: tornado's response object that handles connection response data 173 | """ 174 | log.debug("handle_request(response=%s)" % (response,)) 175 | 176 | if response.code in (200, 500, 502, 503, 504): 177 | log.debug("Connection completed, reconnecting") 178 | elif response.error: 179 | log.error(response.error) 180 | if not self.keep_alive: 181 | self.retry_timeout=-1 182 | else: 183 | log.info("disconnection requested") 184 | if not self.keep_alive: 185 | self.retry_timeout=-1 186 | IOLoop.instance().stop() 187 | 188 | def start(): 189 | """helper method to create a commandline utility""" 190 | parser = argparse.ArgumentParser(prog = sys.argv[0], 191 | description="Event Source Client") 192 | parser.add_argument("-H", 193 | "--host", 194 | dest="host", 195 | default="127.0.0.1", 196 | help="Host to connect to") 197 | # PORT ARGUMENT 198 | parser.add_argument("-P", 199 | "--port", 200 | dest="port", 201 | help="Port to be used connection") 202 | 203 | parser.add_argument("-S", 204 | "--ssl", 205 | dest="ssl", 206 | action="store_true", 207 | help="enables HTTPS scheme support") 208 | 209 | parser.add_argument("-V", 210 | "--validate-cert", 211 | dest="validate_cert", 212 | action="store_true", 213 | help="Forces HTTPS certificate validation") 214 | 215 | parser.add_argument("-d", 216 | "--debug", 217 | dest="debug", 218 | action="store_true", 219 | help="enables debug output") 220 | 221 | parser.add_argument("-r", 222 | "--retry", 223 | dest="retry", 224 | default="0", 225 | help="Reconnection delay (in microseconds)") 226 | 227 | parser.add_argument("-k", 228 | "--keep-reconnecting", 229 | dest="keep_alive", 230 | action="store_true", 231 | help="Keep trying to reconnect on disconnection") 232 | 233 | parser.add_argument("-a", 234 | "--action", 235 | dest="action", 236 | default="poll", 237 | help="The listening action to connect to") 238 | 239 | parser.add_argument("-x", 240 | "--prefix", 241 | dest="prefix", 242 | help="Use given prefix for URL address. For example -x sse will force connection to http://server:port/sse/ instead of http://server:port/") 243 | 244 | parser.add_argument("-u", 245 | "--user", 246 | dest="user", 247 | help="Username for basic authentication") 248 | 249 | parser.add_argument("-p", 250 | "--password", 251 | dest="password", 252 | help="Password for basic authentication") 253 | 254 | parser.add_argument(dest="token", 255 | help="Token to be used for connection") 256 | 257 | args = parser.parse_args() 258 | 259 | if args.debug: 260 | logging.basicConfig(level = logging.DEBUG) 261 | else: 262 | logging.basicConfig(level = logging.INFO) 263 | 264 | ### 265 | 266 | if not args.port: 267 | if args.ssl: 268 | port = "443" 269 | else: 270 | port = "80" 271 | else: 272 | port = args.port 273 | 274 | if args.prefix: 275 | dst = "%s:%s/%s" % (args.host, port, args.prefix) 276 | else: 277 | dst = "%s:%s" % (args.host, port) 278 | 279 | EventSourceClient(url = dst, 280 | action = args.action, 281 | target = args.token, 282 | retry = args.retry, 283 | keep_alive = args.keep_alive, 284 | ssl = args.ssl, 285 | validate_cert = args.validate_cert, 286 | user = args.user, 287 | password = args.password).poll() 288 | 289 | ### 290 | 291 | 292 | if __name__ == "__main__": 293 | start() 294 | 295 | -------------------------------------------------------------------------------- /eventsource/listener.py: -------------------------------------------------------------------------------- 1 | # -+- encoding: utf-8 -+- 2 | """ 3 | .. module:: listener 4 | :platform: Unix 5 | :synopsis: This module provides an eventsource listener based on tornado 6 | 7 | .. moduleauthor:: Bernard Pratz 8 | .. moduleauthor:: Ian Whyman 9 | .. moduleauthor:: Коренберг Марк 10 | 11 | .. note:: 12 | resources: 13 | - http://stackoverflow.com/questions/10665569/websocket-event-source-implementation-to-expose-a-two-way-rpc-to-a-python-dj 14 | - http://stackoverflow.com/questions/8812715/using-a-simple-python-generator-as-a-co-routine-in-a-tornado-async-handler 15 | - http://dev.w3.org/html5/eventsource/#event-stream-interpretation 16 | - http://github.com/guyzmo/event-source-library/ 17 | """ 18 | 19 | from __future__ import unicode_literals, print_function 20 | 21 | import os 22 | import sys 23 | import time 24 | import logging 25 | import argparse 26 | import traceback 27 | 28 | log = logging.getLogger("eventsource.listener") 29 | 30 | if sys.version_info.major == 3: 31 | import http.client as httplib 32 | else: 33 | import httplib 34 | from tornado.escape import json_decode, json_encode 35 | from tornado.concurrent import Future 36 | import tornado.web 37 | import tornado.gen 38 | import tornado.ioloop 39 | import tornado.httpserver 40 | 41 | # Event base 42 | 43 | class Event(object): 44 | """ 45 | Class that defines an event, its behaviour and the matching actions 46 | 47 | Members defined by base Event: 48 | - **target** is the token that matches an event source channel 49 | - **action** contains the name of the action (which shall be in `ACTIONS`) 50 | - **value** contains a list of every lines of the value to be parsed 51 | 52 | Static members: 53 | - content_type field is the Accept header value that is returned on new connections 54 | - **ACTIONS** contains the list of acceptable POST targets. 55 | - Actions defined in base Event: 56 | - **LISTEN** is the GET event that will open an event source communication 57 | - **FINISH** is the POST event that will end a communication started by `LISTEN` 58 | - **RETRY** is the POST event that defines reconnection timeouts for the client 59 | """ 60 | content_type = "text/plain" 61 | 62 | LISTEN = "poll" 63 | FINISH = "close" 64 | RETRY = "retry" 65 | ACTIONS=[FINISH] 66 | 67 | def get_value(self): 68 | """Property to encapsulate processing on value""" 69 | return self._value 70 | 71 | def set_value(self, v): 72 | self._value = v 73 | 74 | value = property(get_value, set_value) 75 | 76 | id = None 77 | 78 | def __init__(self, target, action, value = None): 79 | """ 80 | Creates a new Event object with 81 | :param target: a string matching an open channel 82 | :param action: a string matching an action in the ACTIONS list 83 | :param value: a value to be embedded 84 | """ 85 | self.target = target 86 | self.action = action 87 | self.set_value(value) 88 | 89 | class EventId(object): 90 | """ 91 | Class that defines an event with an id 92 | - defines field `id` using property, using method `get_id()` 93 | """ 94 | cnt = 0 95 | 96 | def get_id(self): 97 | """Method to create id generation behaviour""" 98 | if self.cnt == EventId.cnt: 99 | self.cnt = EventId.cnt 100 | EventId.cnt+=1 101 | return self.cnt 102 | 103 | id = property(get_id) 104 | 105 | # Reusable events 106 | 107 | class StringEvent(Event): 108 | """ 109 | Class that defines a multiline string Event 110 | - overloads `Event.get_value()`, and associates it using a property 111 | - adds a "ping" event 112 | """ 113 | ACTIONS=["ping", Event.FINISH] 114 | def get_value(self): 115 | return [line for line in self._value.split("\n")] 116 | 117 | value = property(get_value, Event.set_value) 118 | 119 | class JSONEvent(Event): 120 | """ 121 | Class that defines a JSON-checked Event 122 | - overloads `Event.get_value()` and `Event.set_value()`, and associates it using a property 123 | - adds a "ping" event 124 | - defines content_type to `application/json` 125 | """ 126 | content_type = "application/json" 127 | 128 | LISTEN = "poll" 129 | FINISH = "close" 130 | ACTIONS=["ping", FINISH] 131 | 132 | def get_value(self): 133 | return [json_encode(self._value)] 134 | 135 | def set_value(self, v): 136 | self._value = json_decode(v) 137 | 138 | value = property(get_value, set_value) 139 | 140 | class StringIdEvent(StringEvent, EventId): 141 | """ 142 | Class that defines a Multiline String Event with id generation 143 | """ 144 | ACTIONS=["ping", Event.RETRY, Event.FINISH] 145 | 146 | id = property(EventId.get_id) 147 | 148 | class JSONIdEvent(JSONEvent, EventId): 149 | """ 150 | Class that defines a JSON-checked Event with id generation 151 | """ 152 | content_type = JSONEvent.content_type 153 | ACTIONS=["ping", Event.RETRY, Event.FINISH] 154 | 155 | id = property(EventId.get_id) 156 | 157 | # EventSource mechanism 158 | 159 | class EventSourceHandler(tornado.web.RequestHandler): 160 | _connected = {} 161 | _lock = {} 162 | def initialize(self, event_class = StringEvent, keepalive = 0): 163 | """ 164 | Takes an Event based class to define the event's handling 165 | :param event_class: defines the kind of event that is expected 166 | :param keepalive: time lapse to wait for sending keepalive messages, in milliseconds. If `0`, keepalive is deactivated. 167 | """ 168 | self._event_class = event_class 169 | self._retry = None 170 | if keepalive is not 0: 171 | self._keepalive = tornado.ioloop.PeriodicCallback(self.push_keepalive, int(keepalive)) 172 | else: 173 | self._keepalive = None 174 | 175 | # Tools 176 | 177 | @tornado.web.asynchronous 178 | def push_keepalive(self): 179 | """ 180 | callback function called by `tornado.ioloop.PeriodicCallback` 181 | """ 182 | log.debug("push_keepalive()") 183 | self.write(": keepalive {}\r\n\r\n".format(str(time.time()))) 184 | self.flush() 185 | 186 | def push(self, event): 187 | """ 188 | For a given event, write event-source outputs on current handler 189 | 190 | :param event: Event based incoming event 191 | """ 192 | log.debug("push({},{},{})".format(event.id, event.action, event.value)) 193 | if hasattr(event, "id"): 194 | self.write("id: {}\r\n".format(str(event.id))) 195 | if self._retry is not None: 196 | self.write("retry: {}\r\n".format(str(self._retry))) 197 | self._retry = None 198 | self.write("event: {}\r\n".format(str(event.action))) 199 | for line in event.value: 200 | self.write("data: {}\r\n".format(str(line))) 201 | self.write("\r\n") 202 | self.flush() 203 | 204 | def buffer_event(self, target, action, value = None): 205 | """ 206 | creates and store an event for the target 207 | 208 | :param target: string identifying current target 209 | :param action: string matching one of Event.ACTIONS 210 | :param value: string containing a value 211 | """ 212 | log.debug("buffer_event({})".format(target)) 213 | self._lock[target].set_result(self._event_class(target, action, value)) 214 | 215 | def is_connected(self, target): 216 | """ 217 | Tells whether an eventsource channel identified by `target` is opened. 218 | 219 | :param target: string identifying a given target 220 | @return true if target is connected 221 | """ 222 | return target in self._connected.values() 223 | 224 | def set_connected(self, target): 225 | """ 226 | registers target as being connected 227 | 228 | :param target: string identifying a given target 229 | 230 | this method will add target to the connected list and create an empty event buffer 231 | """ 232 | log.debug("set_connected({})".format(target)) 233 | self._connected[self] = target 234 | self._lock[target] = Future() 235 | 236 | def set_disconnected(self): 237 | """ 238 | unregisters current handler as being connected 239 | 240 | this method will remove target from the connected list and delete the event buffer 241 | """ 242 | target = None 243 | try: 244 | target = self._connected[self] 245 | log.debug("set_disconnected({})".format(target)) 246 | if self._keepalive: 247 | self._keepalive.stop() 248 | del(self._lock[target]) 249 | del(self._connected[self]) 250 | except Exception as err: 251 | log.error("set_disconnected({},{}): {}", str(self), target, err) 252 | 253 | def write_error(self, status_code, **kwargs): 254 | """ 255 | Overloads the write_error() method of RequestHandler, to 256 | support more explicit messages than only the ones from http.client. 257 | This will end the current eventsource channel. 258 | 259 | :param status_code: error code to be returned 260 | :param mesg: specific message to output (if non-present, http.client error message will be used) 261 | :param exc_info: displays exception trace (if debug mode is enabled) 262 | """ 263 | if self.settings.get("debug") and "exc_info" in kwargs: 264 | # in debug mode, try to send a traceback 265 | self.set_header("Content-Type", "text/plain") 266 | for line in traceback.format_exception(*kwargs["exc_info"]): 267 | self.write(line) 268 | self.finish() 269 | else: 270 | if "mesg" in kwargs: 271 | self.finish("%(code)d: %(message)s" 272 | "%(code)d: %(mesg)s\n".format( 273 | code=status_code, 274 | message=httplib.responses[status_code], 275 | mesg=kwargs["mesg"], 276 | )) 277 | else: 278 | self.finish("%(code)d: %(message)s" 279 | "%(code)d: %(message)s\n".format( 280 | code=status_code, 281 | message=httplib.responses[status_code], 282 | )) 283 | 284 | # Synchronous actions 285 | 286 | def post(self, action, target): 287 | """ 288 | Triggers an event 289 | 290 | :param action: string defining the type of event 291 | :param target: string defining the target handler to send it to 292 | :returns: HTTP error 404 if `target` is not connected 293 | :returns: HTTP error 404 if `action` is not in Event.ACTIONS 294 | :returns: HTTP error 400 if data is not properly formatted. 295 | 296 | this method will look for the request body to get post's data. 297 | """ 298 | log.debug("post({},{})".format(target, action)) 299 | self.set_header("Accept", self._event_class.content_type) 300 | if target not in list(self._connected.values()): 301 | self.send_error(404, mesg="Target is not connected") 302 | elif action not in self._event_class.ACTIONS: 303 | self.send_error(404, mesg="Unknown action requested") 304 | else: 305 | try: 306 | self.buffer_event(target, action, self.request.body) 307 | except ValueError as ve: 308 | self.send_error(400, mesg="Data is not properly formatted:
{}".format(ve)) 309 | 310 | # Asynchronous actions 311 | 312 | def _event_loop(self, future): 313 | """ 314 | for target matching current handler, gets and forwards all events 315 | until Event.FINISH is reached, and then closes the channel. 316 | """ 317 | event = future.result() 318 | log.debug("_event_loop({})".format(event.target)) 319 | if self._event_class.RETRY in self._event_class.ACTIONS: 320 | if event.action == self._event_class.RETRY: 321 | try: 322 | self._retry = int(event.value[0]) 323 | return 324 | except ValueError: 325 | log.error("incorrect retry value: {}".format(event.value)) 326 | if event.action == self._event_class.FINISH: 327 | self.set_disconnected() 328 | self.finish() 329 | return 330 | self.push(event) 331 | self._lock[event.target] = Future() 332 | self._lock[event.target].add_done_callback(self._event_loop) 333 | 334 | 335 | @tornado.web.asynchronous 336 | def get(self, action, target): 337 | """ 338 | Opens a new event_source connection and wait for events to come 339 | 340 | :returns: error 423 if the target token already exists 341 | Redirects to / if action is not matching Event.LISTEN. 342 | """ 343 | log.debug("get({},{})".format(target, action)) 344 | if action == self._event_class.LISTEN: 345 | self.set_header("Content-Type", "text/event-stream") 346 | self.set_header("Cache-Control", "no-cache") 347 | if self.is_connected(target): 348 | self.send_error(423, mesg="Target is already connected") 349 | return 350 | self.set_connected(target) 351 | if self._keepalive: 352 | self._keepalive.start() 353 | self._lock[target].add_done_callback(self._event_loop) 354 | else: 355 | self.redirect("/", permanent = True) 356 | 357 | def on_connection_close(self): 358 | """ 359 | overloads RequestHandler's on_connection_close to disconnect 360 | currents handler on client's socket disconnection. 361 | """ 362 | log.debug("on_connection_close()") 363 | self.set_disconnected() 364 | 365 | ### 366 | 367 | def start(): 368 | """helper method to create a commandline utility""" 369 | parser = argparse.ArgumentParser(prog = sys.argv[0], 370 | description="Event Source Listener") 371 | parser.add_argument("-H", 372 | "--host", 373 | dest="host", 374 | default="0.0.0.0", 375 | help="Host to bind on") 376 | # PORT ARGUMENT 377 | parser.add_argument("-P", 378 | "--port", 379 | dest="port", 380 | default="8888", 381 | help="Port to bind on") 382 | 383 | parser.add_argument("-K", 384 | "--keyfile", 385 | dest="ssl_keyfile", 386 | default="", 387 | help="Path to Key file\nif specified with --certfile, SSL is enabled") 388 | 389 | parser.add_argument("-C", 390 | "--certfile", 391 | dest="ssl_certfile", 392 | default="", 393 | help="Path to CA Cert file\nif specified with --keyfile, SSL is enabled") 394 | 395 | parser.add_argument("-d", 396 | "--debug", 397 | dest="debug", 398 | action="store_true", 399 | help="enables debug output") 400 | 401 | parser.add_argument("-j", 402 | "--json", 403 | dest="json", 404 | action="store_true", 405 | help="to enable JSON Event") 406 | 407 | parser.add_argument("-k", 408 | "--keepalive", 409 | dest="keepalive", 410 | default="0", 411 | help="Keepalive timeout, in milliseconds") 412 | 413 | parser.add_argument("-i", 414 | "--id", 415 | dest="id", 416 | action="store_true", 417 | help="to generate identifiers") 418 | 419 | args = parser.parse_args(sys.argv[1:]) 420 | 421 | if args.debug: 422 | logging.basicConfig(level = logging.DEBUG) 423 | else: 424 | logging.basicConfig(level = logging.INFO) 425 | 426 | if args.json: 427 | if args.id: 428 | chosen_event = JSONIdEvent 429 | else: 430 | chosen_event = JSONEvent 431 | else: 432 | if args.id: 433 | chosen_event = StringIdEvent 434 | else: 435 | chosen_event = StringEvent 436 | 437 | try: 438 | args.keepalive = int(args.keepalive) 439 | except ValueError: 440 | log.error("keepalive takes a numerical value") 441 | sys.exit(1) 442 | 443 | ### 444 | try: 445 | application = tornado.web.Application([ 446 | (r"/(.*)/(.*)", EventSourceHandler, dict(event_class = chosen_event, keepalive = args.keepalive)), 447 | ]) 448 | 449 | if args.ssl_certfile != "" or args.ssl_keyfile != "": 450 | if os.path.exists(args.ssl_certfile) and os.path.exists(args.ssl_keyfile): 451 | application = tornado.httpserver.HTTPServer(application, ssl_options={ 452 | "certfile": args.ssl_certfile, 453 | "keyfile": args.ssl_keyfile, 454 | }) 455 | else: 456 | log.error("[-C|--certfile] and [-K|--keyfile] shall be specified *together* to enable SSL use. SSL is disabled.") 457 | 458 | application.listen(int(args.port)) 459 | tornado.ioloop.IOLoop.instance().start() 460 | except ValueError: 461 | log.error("The port '%d' shall be a numerical value.".format(args.port)) 462 | sys.exit(1) 463 | 464 | ### 465 | 466 | if __name__ == "__main__": 467 | start() 468 | 469 | -------------------------------------------------------------------------------- /eventsource/request.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import argparse 3 | 4 | import json 5 | import urllib2 6 | 7 | def send_json(url, data): 8 | """ 9 | Sends a JSON query to eventsource's URL 10 | 11 | :param url: string url to send to 12 | :param data: string data to send to given URL 13 | """ 14 | if isinstance(data, basestring): 15 | data = json.dumps(json.loads(data)) 16 | else: 17 | data = json.dumps(data) 18 | req = urllib2.Request(url, data, {"Content-Type": "application/json"}) 19 | f = urllib2.urlopen(req) 20 | try: 21 | response = f.read() 22 | return response 23 | finally: 24 | f.close() 25 | 26 | def send_string(url, data): 27 | """ 28 | Sends a string query to eventsource's URL 29 | 30 | :param url: string url to send to 31 | :param data: string data to send to given URL 32 | """ 33 | f = urllib2.urlopen(url, data) 34 | try: 35 | response = f.read() 36 | return response 37 | finally: 38 | f.close() 39 | 40 | def start(): 41 | """helper method to create a commandline utility""" 42 | parser = argparse.ArgumentParser(prog = sys.argv[0], 43 | description="Generates event for Event Source Library") 44 | 45 | parser.add_argument("token", 46 | help="Token to be used for connection") 47 | 48 | parser.add_argument("action", 49 | help="Action to send") 50 | 51 | parser.add_argument("data", 52 | nargs="?", 53 | default="", 54 | help="Data to be sent") 55 | 56 | parser.add_argument("-H", 57 | "--host", 58 | dest="host", 59 | default="127.0.0.1", 60 | help="Host to connect to") 61 | # PORT ARGUMENT 62 | parser.add_argument("-P", 63 | "--port", 64 | dest="port", 65 | default="8888", 66 | help="Port to be used connection") 67 | 68 | parser.add_argument("-j", 69 | "--json", 70 | dest="json", 71 | action="store_true", 72 | help="Treat data as JSON") 73 | 74 | args = parser.parse_args(sys.argv[1:]) 75 | 76 | try: 77 | if args.json: 78 | print send_json("http://%(host)s:%(port)s/%(action)s/%(token)s" % args.__dict__, args.data) 79 | else: 80 | print send_string("http://%(host)s:%(port)s/%(action)s/%(token)s" % args.__dict__, args.data) 81 | sys.exit(0) 82 | except Exception, err: 83 | print "Unable to send request (%s): %s" % (err, err.readline().split("")[-1].split("")[0]) 84 | sys.exit(1) 85 | 86 | if __name__ == "__main__": 87 | start() 88 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # setuptools import 2 | from setuptools import setup, find_packages 3 | 4 | import os, sys 5 | 6 | def read(*names): 7 | values = dict() 8 | for name in names: 9 | for ext in ['.txt','.md','.rst','']: 10 | filename = name+ext 11 | if os.path.isfile(filename): 12 | value = open(filename).read() 13 | break 14 | else: 15 | value = '' 16 | values[name] = value 17 | return values 18 | 19 | long_description=""" 20 | %(README)s 21 | 22 | See http://packages.python.org/eventsource/ for the full documentation 23 | See https://github.com/guyzmo/event-source-library for latest sources and for patches 24 | 25 | News 26 | ==== 27 | 28 | %(CHANGES)s 29 | 30 | """ % read('README', 'CHANGES') 31 | 32 | setup(name="eventsource", 33 | version="1.2", 34 | description="Event Source Library", 35 | long_description=long_description, 36 | author="Bernard Pratz", 37 | author_email="guyzmo+github@m0g.net", 38 | install_requires = [ 39 | 'tornado>=4.4', 40 | 'pycurl', 41 | ] + (['future'] if sys.version_info.major == 2 else []), 42 | packages = find_packages(exclude=['examples', 'tests']), 43 | url='http://packages.python.org/eventsource/', 44 | include_package_data=True, 45 | zip_safe=False, 46 | license="GPLv3", 47 | classifiers = ["Topic :: Internet :: WWW/HTTP :: Dynamic Content", 48 | "Intended Audience :: Developers", 49 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 50 | "Operating System :: OS Independent", 51 | "Programming Language :: Python", 52 | "Topic :: Utilities"], 53 | entry_points=""" 54 | # -*- Entry points: -*- 55 | [console_scripts] 56 | eventsource-server = eventsource.listener:start 57 | eventsource-client = eventsource.client:start 58 | eventsource-request = eventsource.request:start 59 | """, 60 | ) 61 | --------------------------------------------------------------------------------