pax_global_header00006660000000000000000000000064125721162410014513gustar00rootroot0000000000000052 comment=3c9335d56f9adce86eed7cef669762e298bf4c35 rows-0.1.1/000077500000000000000000000000001257211624100125045ustar00rootroot00000000000000rows-0.1.1/.gitignore000066400000000000000000000001531257211624100144730ustar00rootroot00000000000000*.egg-info/ *.pyc *~ .*.sw? .coverage .directory .env .idea/* .tox MANIFEST build/* dist/* reg_settings.py rows-0.1.1/AUTHORS000066400000000000000000000006061257211624100135560ustar00rootroot00000000000000rows: Authors and Contributors ============================== Project page: . Author/Maintainer ----------------- Created and maintained by Álvaro Justen -- contact at: - - - Contributors ------------ - Érico Andrei rows-0.1.1/CHANGELOG.md000066400000000000000000000024701257211624100143200ustar00rootroot00000000000000# rows' Log of Changes ## Version `0.2.0` (under development) **Released on: (under development)** - Enhance README - Refactor `export_to_txt` - Support lazy objects on `create_table` - Add `samples` parameter to `create_table` - Add plugin JSON (thanks [@sxslex](https://github.com/sxslex)) ## Version `0.1.1` **Released on: 2015-09-03** - Fix code to run on Windows (thanks [@sxslex](https://github.com/sxslex)) - Fix locale (name, default name etc.) - Remove `filemagic` dependency (waiting for `python-magic` to be available on PyPI) - Write log of changes for `0.1.0` and `0.1.1` ## Version `0.1.0` **Released on: 2015-08-29** - Implement `Table` and its basic methods - Implement basic plugin support with many utilities and the following formats: - `csv` (input/output) - `html` (input/output) - `txt` (output) - `xls` (input/output) - Implement the following field types - many of them with locale support: - `ByteField` - `BoolField` - `IntegerField` - `FloatField` - `DecimalField` - `PercentField` - `DateField` - `DatetimeField` - `UnicodeField` - Implement basic `Table` operations: - `sum` - `join` - `transform` - `serialize` - Implement a command-line interface with the following subcommands: - `convert` - `join` - `sort` - `sum` - Add examples to the repository rows-0.1.1/LICENSE000066400000000000000000001045131257211624100135150ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. 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. 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. 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. 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. 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. 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. 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. 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. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "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. 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. A "covered work" means either the unmodified Program or a work based on the Program. 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. 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. 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. 1. Source Code. 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. 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. 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. 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. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. 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. 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. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 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. 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. 4. Conveying Verbatim Copies. 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. 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. 5. Conveying Modified Source Versions. 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: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 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". 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. 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. 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. 6. Conveying Non-Source Forms. 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: 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. 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. 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. 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. 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. 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. 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. "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. 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). 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. 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. 7. Additional Terms. "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. 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. 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: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 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 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 d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 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. 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. 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. 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. 8. Termination. 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). 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. 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. 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. 9. Acceptance Not Required for Having Copies. 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. 10. Automatic Licensing of Downstream Recipients. 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. 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. 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. 11. Patents. 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". 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. 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. 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. 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. 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. 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. 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. 12. No Surrender of Others' Freedom. 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. 13. Use with the GNU Affero General Public License. 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. 14. Revised Versions of this License. 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. 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. 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. 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. 15. Disclaimer of Warranty. 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. 16. Limitation of Liability. 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. 17. Interpretation of Sections 15 and 16. 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. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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, either version 3 of the License, or (at your option) any later version. 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. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . rows-0.1.1/Makefile000066400000000000000000000006621257211624100141500ustar00rootroot00000000000000test: nosetests -dsv --with-yanc --with-coverage --cover-package rows tests/*.py clean: find -regex '.*\.pyc' -exec rm {} \; find -regex '.*~' -exec rm {} \; rm -rf reg-settings.py rm -rf MANIFEST dist build *.egg-info install: make clean make uninstall python setup.py install uninstall: pip uninstall -y rows lint: pylint rows/*.py lint-tests: pylint tests/*.py .PHONY: test clean lint lint-tests install uninstall rows-0.1.1/README.markdown000066400000000000000000000131531257211624100152100ustar00rootroot00000000000000# rows [![Join the chat at https://gitter.im/turicas/rows](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/turicas/rows?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) No matter in which format your tabular data is: `rows` will import it, automatically detect types and give you high-level Python objects so you can start **working with the data** instead of **trying to parse it**. It is also locale-and-unicode aware. :) ## Architecture The library is composed by: - A common interface to tabular data (the `Table` class) - A set of plugins to populate `Table` objects (CSV, XLS, HTML, TXT -- more coming soon!) - A set of common fields (such as `BoolField`, `IntegerField`) which know exactly how to serialize and deserialize data for each object type you'll get - A set of utilities (such as field type recognition) to help working with tabular data - A command-line interface so you can have easy access to the most used features: convert between formats, sum, join and sort tables. Just `import rows` and relax. ## Installation Directly from [PyPI](http://pypi.python.org/pypi/rows): pip install rows Or from source: git clone https://github.com/turicas/rows.git cd rows python setup.py install ## Basic Usage You can create a `Table` object and populate it with some data: ```python from collections import OrderedDict from rows import fields, Table my_fields = OrderedDict([('name', fields.UnicodeField), ('age', fields.IntegerField), ('married', fields.BoolField)]) table = Table(fields=my_fields) table.append({'name': u'Álvaro Justen', 'age': 28, 'married': False}) table.append({'name': u'Another Guy', 'age': 42, 'married': True}) ``` Then you can iterate over it: ```python def print_person(person): married = 'is married' if person.married else 'is not married' print u'{} is {} years old and {}'.format(person.name, person.age, married) for person in table: print_person(person) # namedtuples are returned ``` You'll see: ``` Álvaro Justen is 28 years old and is not married Another Guy is 42 years old and is married ``` As you specified field types (`my_fields`) you don't need to insert data using the correct types. Actually you can insert strings and the library you automatically convert it for you: ```python table.append({'name': '...', 'age': '', 'married': 'false'}) print_person(table[-1]) # yes, you can index it! ``` And the output: ``` ... is None years old and is not married ``` ### Importing Data `rows` will help you importing data: its plugins will do the hard job of parsing each supported file format so you don't need to. They can help you exporting data also. For example, let's download a CSV from the Web and import it: ```python import requests import rows from io import BytesIO url = 'http://unitedstates.sunlightfoundation.com/legislators/legislators.csv' csv = requests.get(url).content # Download CSV data legislators = rows.import_from_csv(BytesIO(csv)) # already imported! print 'Hey, rows automatically identified the types:' for field_name, field_type in legislators.fields.items(): print '{} is {}'.format(field_name, field_type) ``` And you'll see something like this: ``` [...] in_office is gender is [...] birthdate is ``` We can then work on this data: ```python women_in_office = filter(lambda row: row.in_office and row.gender == 'F', legislators) men_in_office = filter(lambda row: row.in_office and row.gender == 'M', legislators) print 'Women vs Men: {} vs {}'.format(len(women_in_office), len(men_in_office)) ``` Now, let's compare ages: ```python legislators.order_by('birthdate') older, younger = legislators[-1], legislators[0] print '{}, {} is older than {}, {}'.format(older.lastname, older.firstname, younger.lastname, younger.firstname) ``` The output: ``` Stefanik, Elise is older than Byrd, Robert ``` > Note that **native Python objects** are returned for each row! The library > recognizes each field type and convert data *automagically*. ### Exporting Data Now it's time to export this data using another plugin: HTML! It's pretty easy: ```python rows.export_to_html(legislators, 'legislators.html') ``` And you'll get: ``` $ head legislators.html ``` Now you have finished the quickstart guide. See the `examples` folder for more examples. ### Available Plugins - CSV: use `rows.import_from_csv` and `rows.export_to_csv` - HTML: use `rows.import_from_html` and `rows.export_to_html` - XLS: use `rows.import_from_xls` and `rows.export_to_xls` - TXT: use `rows.export_to_csv` We'll be adding support for more plugins soon (like ODS, PDF, JSON etc.) -- actually we're going to re-design the plugin interface so you can create your own easily. ## Command-Line Interface TODO. Run `rows --help` and see `rows/cli.py`. ## Locale TODO. See `rows/localization.py`. ## Operations Available operations: `join`, `transform` and `serialize`. TODO. See `rows/operations.py`. ## License This library is released under the [GNU General Public License version 3](http://www.gnu.org/licenses/gpl-3.0.html). ## Related projects - - - - messytables - tablib - pandas' DataFrame rows-0.1.1/examples/000077500000000000000000000000001257211624100143225ustar00rootroot00000000000000rows-0.1.1/examples/convert.sh000077500000000000000000000005021257211624100163360ustar00rootroot00000000000000#!/bin/bash URL="http://cidades.ibge.gov.br/comparamun/compara.php?idtema=1&codv=v01&coduf=43" LOCALE="pt_BR.UTF-8" FILENAME="populacao-rs" rows convert --input-locale $LOCALE $URL $FILENAME.csv rows convert $FILENAME.csv $FILENAME.html rows convert $FILENAME.html $FILENAME.xls rows convert $FILENAME.xls $FILENAME.txt rows-0.1.1/examples/join.sh000077500000000000000000000002461257211624100156220ustar00rootroot00000000000000#!/bin/bash KEYS="uf,municipio" SOURCE1="populacao-sudeste.csv" SOURCE2="area-sudeste.csv" DESTINATION="sudeste.csv" rows join $KEYS $SOURCE1 $SOURCE2 $DESTINATION rows-0.1.1/examples/slip_opinions.py000066400000000000000000000010441257211624100175600ustar00rootroot00000000000000# coding: utf-8 # This example was based on: # https://github.com/compjour/search-script-scrape/blob/master/scripts/42.py from io import BytesIO from urlparse import urljoin import requests import rows from rows.plugins.html import tag_to_dict url = 'http://www.supremecourt.gov/opinions/slipopinions.aspx' html = requests.get(url).content table = rows.import_from_html(BytesIO(html), index=1, preserve_html=True) for element in table: attributes = tag_to_dict(element.name) print attributes['text'], urljoin(url, attributes['href']) rows-0.1.1/examples/sort.sh000077500000000000000000000003221257211624100156450ustar00rootroot00000000000000#!/bin/bash URL="http://cidades.ibge.gov.br/comparamun/compara.php?idtema=1&codv=v01&coduf=43" LOCALE="pt_BR.UTF-8" FILENAME="populacao-rs-sorted" rows sort --input-locale $LOCALE ^pessoas $URL $FILENAME.csv rows-0.1.1/examples/sum.sh000077500000000000000000000017501257211624100154700ustar00rootroot00000000000000#!/bin/bash # population SOURCE1="http://cidades.ibge.gov.br/comparamun/compara.php?idtema=1&codv=v01&coduf=33" SOURCE2="http://cidades.ibge.gov.br/comparamun/compara.php?idtema=1&codv=v01&coduf=35" SOURCE3="http://cidades.ibge.gov.br/comparamun/compara.php?idtema=1&codv=v01&coduf=31" SOURCE4="http://cidades.ibge.gov.br/comparamun/compara.php?idtema=1&codv=v01&coduf=32" DESTINATION="populacao-sudeste.csv" LOCALE="pt_BR.UTF-8" rows sum --input-locale $LOCALE \ $SOURCE1 $SOURCE2 $SOURCE3 $SOURCE4 \ $DESTINATION # area SOURCE5="http://cidades.ibge.gov.br/comparamun/compara.php?idtema=16&codv=v01&coduf=33" SOURCE6="http://cidades.ibge.gov.br/comparamun/compara.php?idtema=16&codv=v01&coduf=35" SOURCE7="http://cidades.ibge.gov.br/comparamun/compara.php?idtema=16&codv=v01&coduf=31" SOURCE8="http://cidades.ibge.gov.br/comparamun/compara.php?idtema=16&codv=v01&coduf=32" DESTINATION="area-sudeste.csv" rows sum --input-locale $LOCALE \ $SOURCE5 $SOURCE6 $SOURCE7 $SOURCE8 \ $DESTINATION rows-0.1.1/examples/tests_uwsgi_log.py000066400000000000000000000034071257211624100201210ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import datetime import unittest from rows.table import Table from uwsgi_log_plugin import import_from_uwsgi_log class UwsgiLogPluginTestCase(unittest.TestCase): def test_import_from_uwsgi_log(self): filename = 'uwsgi.log' table = import_from_uwsgi_log(filename) self.assertEqual(len(table), 2) first = table.Row(pid=879, ip=u'127.0.0.1', datetime=datetime.datetime(2015, 6, 1, 11, 23, 16), http_verb=u'GET', http_path=u'/something', generation_time=0.17378, http_version=1.1, http_status=404) second = table.Row(pid=31460, ip=u'127.0.1.1', datetime=datetime.datetime(2015, 7, 15, 23, 49, 20), http_verb=u'OPTIONS', http_path=u'/about', generation_time=0.000466, http_version=1.1, http_status=200) self.assertEqual(table[0], first) self.assertEqual(table[1], second) rows-0.1.1/examples/usa_legislators.py000066400000000000000000000022701257211624100200750ustar00rootroot00000000000000# coding: utf-8 # This example was based on: # https://github.com/compjour/search-script-scrape/blob/master/scripts/101.py from io import BytesIO import requests import rows # Capture url = 'http://unitedstates.sunlightfoundation.com/legislators/legislators.csv' csv = BytesIO(requests.get(url).content) # Normalize table = rows.import_from_csv(csv) # Analyze total = len(table) total_in_office = len(filter(lambda row: row.in_office, table)) men = len(filter(lambda row: row.gender == 'M', table)) men_in_office = len(filter(lambda row: row.gender == 'M' and row.in_office, table)) women = len(filter(lambda row: row.gender == 'F', table)) women_in_office = len(filter(lambda row: row.gender == 'F' and row.in_office, table)) # View print (' Men: {}/{} ({:02.2f}%), in office: {}/{} ({:02.2f}%)' .format(men, total, 100 * men / float(total), men_in_office, total_in_office, 100 * men_in_office / float(total))) print ('Women: {}/{} ({:02.2f}%), in office: {}/{} ({:02.2f}%)' .format(women, total, 100 * women / float(total), women_in_office, total_in_office, 100 * women_in_office / float(total))) rows-0.1.1/examples/uwsgi.log000066400000000000000000000075351257211624100161750ustar00rootroot00000000000000*** Starting uWSGI 2.0.8 (64bit) on [Mon Jun 1 11:08:58 2015] *** compiled with version: 4.8.2 on 01 June 2015 11:01:28 os: Linux-3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 nodename: localhost.localdomain machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/ubuntu writing pidfile to /home/ubuntu/uwsgi/uwsgi.pid detected binary path: /home/ubuntu/venv/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! chdir() to /home/ubuntu/repo your processes number limit is 7862 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to TCP address 127.0.0.1:8001 fd 3 Python version: 2.7.6 (default, Mar 22 2014, 23:03:41) [GCC 4.8.2] Set PythonHome to /home/ubuntu/venv *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0x14d9cf0 your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 363840 bytes (355 KB) for 4 cores *** Operational MODE: preforking *** WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x14d9cf0 pid: 32310 (default app) *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 32310) spawned uWSGI worker 1 (pid: 32317, cores: 1) spawned uWSGI worker 2 (pid: 32318, cores: 1) spawned uWSGI worker 3 (pid: 32319, cores: 1) spawned uWSGI worker 4 (pid: 32320, cores: 1) *** Stats server enabled on 127.0.0.1:8002 fd: 16 *** SIGINT/SIGQUIT received...killing workers... worker 1 buried after 1 seconds worker 2 buried after 1 seconds worker 3 buried after 1 seconds worker 4 buried after 1 seconds goodbye to uWSGI. VACUUM: pidfile removed. *** Starting uWSGI 2.0.8 (64bit) on [Mon Jun 1 11:20:46 2015] *** compiled with version: 4.8.2 on 01 June 2015 11:01:28 os: Linux-3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 nodename: localhost.localdomain machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/ubuntu writing pidfile to /home/ubuntu/uwsgi/uwsgi.pid detected binary path: /home/ubuntu/venv/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! chdir() to /home/ubuntu/repo your processes number limit is 7862 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to TCP address 127.0.0.1:8001 fd 3 Python version: 2.7.6 (default, Mar 22 2014, 23:03:41) [GCC 4.8.2] Set PythonHome to /home/ubuntu/venv *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0xf6dcf0 your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 363840 bytes (355 KB) for 4 cores *** Operational MODE: preforking *** WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0xf6dcf0 pid: 872 (default app) *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 872) spawned uWSGI worker 1 (pid: 879, cores: 1) spawned uWSGI worker 2 (pid: 880, cores: 1) spawned uWSGI worker 3 (pid: 881, cores: 1) spawned uWSGI worker 4 (pid: 882, cores: 1) *** Stats server enabled on 127.0.0.1:8002 fd: 16 *** [pid: 879|app: 0|req: 1/1] 127.0.0.1 () {40 vars in 743 bytes} [Mon Jun 1 11:23:16 2015] GET /something => generated 93 bytes in 173780 micros (HTTP/1.1 404) 2 headers in 80 bytes (1 switches on core 0) [pid: 31460|app: 0|req: 21/2786] 127.0.1.1 () {46 vars in 840 bytes} [Wed Jul 15 23:49:20 2015] OPTIONS /about => generated 0 bytes in 466 micros (HTTP/1.1 200) 6 headers in 327 bytes (1 switches on core 0) rows-0.1.1/examples/uwsgi_log_plugin.py000066400000000000000000000035531257211624100202570ustar00rootroot00000000000000# coding: utf-8 from __future__ import unicode_literals import datetime import re from collections import OrderedDict import rows.fields from rows.table import Table REGEXP_UWSGI_LOG = re.compile(r'\[pid: ([0-9]+)\|app: [0-9]+\|req: ' r'[0-9]+/[0-9]+\] ' r'([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+) .+ \[(.+)\] ' r'([^ ]+) (.+) => generated .+ in ([0-9]+) ' r'micros \(HTTP/([^ ]+) ([^)]+)\)') UWSGI_FIELDS = OrderedDict([('pid', rows.fields.IntegerField), ('ip', rows.fields.UnicodeField), ('datetime', rows.fields.DatetimeField), ('http_verb', rows.fields.UnicodeField), ('http_path', rows.fields.UnicodeField), ('generation_time', rows.fields.FloatField), ('http_version', rows.fields.FloatField), ('http_status', rows.fields.IntegerField)]) UWSGI_DATETIME_FORMAT = '%a %b %d %H:%M:%S %Y' strptime = datetime.datetime.strptime def import_from_uwsgi_log(filename): fields = UWSGI_FIELDS.keys() table = Table(fields=UWSGI_FIELDS) with open(filename) as fobj: for line in fobj: result = REGEXP_UWSGI_LOG.findall(line) if result: data = list(result[0]) # Convert datetime data[2] = strptime(data[2], UWSGI_DATETIME_FORMAT) # Convert generation time (micros -> seconds) data[5] = float(data[5]) / 1000000 table.append({field_name: value for field_name, value in zip(fields, data)}) return table if __name__ == '__main__': table = import_from_uwsgi_log('uwsgi.log') for row in table: print row rows-0.1.1/requirements/000077500000000000000000000000001257211624100152275ustar00rootroot00000000000000rows-0.1.1/requirements/development.txt000066400000000000000000000000771257211624100203160ustar00rootroot00000000000000-r production.txt # Test tools nose yanc coverage pylint ipdb rows-0.1.1/requirements/production.txt000066400000000000000000000000511257211624100201520ustar00rootroot00000000000000click lxml requests unicodecsv xlrd xlwt rows-0.1.1/rows/000077500000000000000000000000001257211624100134765ustar00rootroot00000000000000rows-0.1.1/rows/__init__.py000066400000000000000000000010501257211624100156030ustar00rootroot00000000000000# coding: utf-8 # General imports from rows.operations import join, serialize, transform from rows.table import Table from rows.localization import locale_context # Plugin imports from rows.plugins.txt import export_to_txt try: from rows.plugins.csv import import_from_csv, export_to_csv except ImportError: pass try: from rows.plugins.xls import import_from_xls, export_to_xls except ImportError: pass try: from rows.plugins.html import import_from_html, export_to_html except ImportError: pass __version__ = '0.1.1' rows-0.1.1/rows/cli.py000077500000000000000000000102651257211624100146260ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # TODO: test this whole module # TODO: add option to pass 'create_table' options in command-line (like force # fields) import click import rows from rows.utils import import_from_uri, export_to_uri DEFAULT_INPUT_ENCODING = 'utf-8' DEFAULT_OUTPUT_ENCODING = 'utf-8' DEFAULT_INPUT_LOCALE = 'C' DEFAULT_OUTPUT_LOCALE = 'C' @click.group() def cli(): pass @cli.command(help='Convert table on `source` URI to `destination`') @click.option('--input-encoding', default=DEFAULT_INPUT_ENCODING) @click.option('--output-encoding', default=DEFAULT_OUTPUT_ENCODING) @click.option('--input-locale', default=DEFAULT_INPUT_LOCALE) @click.option('--output-locale', default=DEFAULT_OUTPUT_LOCALE) @click.argument('source') @click.argument('destination') def convert(input_encoding, output_encoding, input_locale, output_locale, source, destination): with rows.locale_context(input_locale): table = import_from_uri(source) with rows.locale_context(output_locale): export_to_uri(destination, table) @cli.command(help='Join tables from `source` URIs using `key(s)` to group rows and save into `destination`') @click.option('--input-encoding', default=DEFAULT_INPUT_ENCODING) @click.option('--output-encoding', default=DEFAULT_OUTPUT_ENCODING) @click.option('--input-locale', default=DEFAULT_INPUT_LOCALE) @click.option('--output-locale', default=DEFAULT_OUTPUT_LOCALE) @click.argument('keys') @click.argument('sources', nargs=-1, required=True) @click.argument('destination') def join(input_encoding, output_encoding, input_locale, output_locale, keys, sources, destination): keys = [key.strip() for key in keys.split(',')] with rows.locale_context(input_locale): tables = [import_from_uri(source) for source in sources] result = rows.join(keys, tables) with rows.locale_context(output_locale): export_to_uri(destination, result) @cli.command(help='Sort from `source` by `key(s)` and save into `destination`') @click.option('--input-encoding', default=DEFAULT_INPUT_ENCODING) @click.option('--output-encoding', default=DEFAULT_OUTPUT_ENCODING) @click.option('--input-locale', default=DEFAULT_INPUT_LOCALE) @click.option('--output-locale', default=DEFAULT_OUTPUT_LOCALE) @click.argument('key') @click.argument('source') @click.argument('destination') def sort(input_encoding, output_encoding, input_locale, output_locale, key, source, destination): key = key.replace('^', '-') with rows.locale_context(input_locale): table = import_from_uri(source) table.order_by(key) with rows.locale_context(output_locale): export_to_uri(destination, table) @cli.command(help='Sum tables from `source` URIs and save into `destination`') @click.option('--input-encoding', default=DEFAULT_INPUT_ENCODING) @click.option('--output-encoding', default=DEFAULT_OUTPUT_ENCODING) @click.option('--input-locale', default=DEFAULT_INPUT_LOCALE) @click.option('--output-locale', default=DEFAULT_OUTPUT_LOCALE) @click.argument('sources', nargs=-1, required=True) @click.argument('destination') def sum(input_encoding, output_encoding, input_locale, output_locale, sources, destination): with rows.locale_context(input_locale): tables = [import_from_uri(source) for source in sources] result = tables[0] for table in tables[1:]: result = result + table with rows.locale_context(output_locale): export_to_uri(destination, result) if __name__ == '__main__': cli() rows-0.1.1/rows/fields.py000066400000000000000000000316341257211624100153250ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import collections import datetime import locale import re import types from decimal import Decimal, InvalidOperation # Order matters here __all__ = ['BoolField', 'IntegerField', 'FloatField', 'DatetimeField', 'DateField', 'DecimalField', 'PercentField', 'UnicodeField', 'ByteField', 'Field'] REGEXP_ONLY_NUMBERS = re.compile('[^0-9]') SHOULD_NOT_USE_LOCALE = True # This variable is changed by rows.locale_manager NULL = (b'-', b'null', b'none', b'nil') class Field(object): """Base Field class - all fields should inherit from this As the fallback for all other field types are the ByteField, this Field actually implements what is expected in the ByteField """ TYPE = types.NoneType @classmethod def serialize(cls, value, *args, **kwargs): """Serialize a value to be exported `cls.serialize` should always return an unicode value, except for ByteField """ if value is None: value = '' return value @classmethod def deserialize(cls, value, *args, **kwargs): """Deserialize a value just after importing it `cls.deserialize` should always return a value of type `cls.TYPE` or `None`. """ if isinstance(value, cls.TYPE): return value elif is_null(value): return None else: return value class ByteField(Field): """Field class to represent byte arrays Is not locale-aware (does not need to be) """ TYPE = types.StringType @classmethod def serialize(cls, value, *args, **kwargs): if value is None: value = '' return cls.TYPE(value) @classmethod def deserialize(cls, value, *args, **kwargs): if value is None: return None else: return cls.TYPE(value) class BoolField(Field): """Base class to representing boolean Is not locale-aware (if you need to, please customize by changing its attributes like `TRUE_VALUES` and `FALSE_VALUES`) """ TYPE = types.BooleanType SERIALIZED_VALUES = {True: 'true', False: 'false', None: ''} TRUE_VALUES = (b'true', b'1', b'yes') FALSE_VALUES = (b'false', b'0', b'no') @classmethod def serialize(cls, value, *args, **kwargs): return cls.SERIALIZED_VALUES[value] @classmethod def deserialize(cls, value, *args, **kwargs): value = super(BoolField, cls).deserialize(value) if value is None or isinstance(value, cls.TYPE): return value value = as_string(value) if value in cls.TRUE_VALUES: return True elif value in cls.FALSE_VALUES: return False else: raise ValueError('Value is not boolean') class IntegerField(Field): """Field class to represent integer Is locale-aware """ TYPE = types.IntType @classmethod def serialize(cls, value, *args, **kwargs): if value is None: return '' if SHOULD_NOT_USE_LOCALE: return types.UnicodeType(value) else: grouping = kwargs.get('grouping', None) return locale.format('%d', value, grouping=grouping) @classmethod def deserialize(cls, value, *args, **kwargs): value = super(IntegerField, cls).deserialize(value) if value is None or isinstance(value, cls.TYPE): return value converted = int(value) if SHOULD_NOT_USE_LOCALE else locale.atoi(value) float_equivalent = FloatField.deserialize(value, *args, **kwargs) if float_equivalent == converted: return converted else: raise ValueError("It's float, not integer") class FloatField(Field): """Field class to represent float Is locale-aware """ TYPE = types.FloatType @classmethod def serialize(cls, value, *args, **kwargs): if value is None: return '' if SHOULD_NOT_USE_LOCALE: return types.UnicodeType(value) else: grouping = kwargs.get('grouping', None) return locale.format('%f', value, grouping=grouping) @classmethod def deserialize(cls, value, *args, **kwargs): value = super(FloatField, cls).deserialize(value) if value is None or isinstance(value, cls.TYPE): return value value = as_string(value) if SHOULD_NOT_USE_LOCALE: return float(value) else: return locale.atof(value) class DecimalField(Field): """Field class to represent decimal data (as Python's decimal.Decimal) Is locale-aware """ TYPE = Decimal @classmethod def serialize(cls, value, *args, **kwargs): if value is None: return '' value_as_string = types.UnicodeType(value) if SHOULD_NOT_USE_LOCALE: return value_as_string else: grouping = kwargs.get('grouping', None) has_decimal_places = value_as_string.find('.') != -1 if not has_decimal_places: string_format = '%d' else: decimal_places = len(value_as_string.split('.')[1]) string_format = '%.{}f'.format(decimal_places) return locale.format(string_format, value, grouping=grouping) @classmethod def deserialize(cls, value, *args, **kwargs): value = super(DecimalField, cls).deserialize(value) if value is None or isinstance(value, cls.TYPE): return value if SHOULD_NOT_USE_LOCALE: try: return Decimal(value) except InvalidOperation: raise ValueError("Can't be {}".format(cls.__name__)) else: locale_vars = locale.localeconv() decimal_separator = locale_vars['decimal_point'] interesting_vars = ['decimal_point', 'mon_decimal_point', 'mon_thousands_sep', 'negative_sign', 'positive_sign', 'thousands_sep'] chars = (locale_vars[x].replace('.', '\.').replace('-', '\-') for x in interesting_vars) interesting_chars = ''.join(set(chars)) regexp = re.compile(r'[^0-9{} ]'.format(interesting_chars)) if regexp.findall(value): raise ValueError("Can't be {}".format(cls.__name__)) parts = [REGEXP_ONLY_NUMBERS.subn('', number)[0] for number in value.split(decimal_separator)] if len(parts) > 2: raise ValueError("Can't deserialize with this locale.") try: value = Decimal(parts[0]) if len(parts) == 2: decimal_places = len(parts[1]) value = value + (Decimal(parts[1]) / (10 ** decimal_places)) except InvalidOperation: raise ValueError("Can't be {}".format(cls.__name__)) return value class PercentField(DecimalField): """Field class to represent percent values Is locale-aware (inherit this behaviour from `rows.DecimalField`) """ @classmethod def serialize(cls, value, *args, **kwargs): value = Decimal(str(value * 100)[:-2]) value = super(PercentField, cls).serialize(value, *args, **kwargs) return '{}%'.format(value) @classmethod def deserialize(cls, value, *args, **kwargs): if isinstance(value, cls.TYPE): return value elif is_null(value): return None value = as_string(value) if '%' not in value: raise ValueError("Can't be {}".format(cls.__name__)) value = value.replace('%', '') return super(PercentField, cls).deserialize(value) / 100 class DateField(Field): """Field class to represent date Is not locale-aware (does not need to be) """ TYPE = datetime.date INPUT_FORMAT = '%Y-%m-%d' OUTPUT_FORMAT = '%Y-%m-%d' @classmethod def serialize(cls, value, *args, **kwargs): if value is None: return '' return types.UnicodeType(value.strftime(cls.OUTPUT_FORMAT)) @classmethod def deserialize(cls, value, *args, **kwargs): value = super(DateField, cls).deserialize(value) if value is None or isinstance(value, cls.TYPE): return value value = as_string(value) dt_object = datetime.datetime.strptime(value, cls.INPUT_FORMAT) return datetime.date(dt_object.year, dt_object.month, dt_object.day) class DatetimeField(Field): """Field class to represent date-time Is not locale-aware (does not need to be) """ TYPE = datetime.datetime DATETIME_REGEXP = re.compile('^([0-9]{4})-([0-9]{2})-([0-9]{2})[ T]' '([0-9]{2}):([0-9]{2}):([0-9]{2})$') @classmethod def serialize(cls, value, *args, **kwargs): if value is None: return '' return types.UnicodeType(value.isoformat()) @classmethod def deserialize(cls, value, *args, **kwargs): value = super(DatetimeField, cls).deserialize(value) if value is None or isinstance(value, cls.TYPE): return value value = as_string(value) # TODO: may use iso8601 groups = cls.DATETIME_REGEXP.findall(value) if not groups: raise ValueError("Can't be {}".format(cls.__name__)) else: return datetime.datetime(*[int(x) for x in groups[0]]) class UnicodeField(Field): """Field class to represent unicode strings Is not locale-aware (does not need to be) """ TYPE = types.UnicodeType @classmethod def deserialize(cls, value, *args, **kwargs): value = super(UnicodeField, cls).deserialize(value) if value is None: return None if type(value) is cls.TYPE: return value elif 'encoding' in kwargs: return as_string(value).decode(kwargs['encoding']) else: return cls.TYPE(value) AVAILABLE_FIELD_TYPES = [locals()[element] for element in __all__ if 'Field' in element and element != 'Field'] def as_string(value): if isinstance(value, types.StringTypes): return value else: return types.StringType(value) def is_null(value): if value is None: return True value_str = as_string(value).strip().lower() return not value_str or value_str in NULL def detect_types(field_names, field_values, field_types=AVAILABLE_FIELD_TYPES, *args, **kwargs): """Where the magic happens""" # TODO: may receive 'type hints' # TODO: should support receiving unicode objects directly # TODO: should expect data in unicode or will be able to use binary data? number_of_fields = len(field_names) columns = zip(*[row for row in field_values if len(row) == number_of_fields]) if len(columns) != number_of_fields: raise ValueError('Number of fields differ') none_type = set([type(None)]) detected_types = collections.OrderedDict([(field_name, None) for field_name in field_names]) encoding = kwargs.get('encoding', None) for index, field_name in enumerate(field_names): data = set([value for value in set(columns[index]) if not is_null(value)]) if not data: # all rows with an empty field -> ByteField (can't identify) identified_type = ByteField else: # ok, let's try to identify the type of this column by # converting every non-null value in the sample possible_types = list(field_types) for value in data: cant_be = set() for type_ in possible_types: try: type_.deserialize(value, *args, **kwargs) except (ValueError, TypeError): cant_be.add(type_) for type_to_remove in cant_be: possible_types.remove(type_to_remove) identified_type = possible_types[0] # priorities matter detected_types[field_name] = identified_type return detected_types rows-0.1.1/rows/localization.py000066400000000000000000000012151257211624100165370ustar00rootroot00000000000000# coding: utf-8 from __future__ import unicode_literals import contextlib import locale import types import rows.fields @contextlib.contextmanager def locale_context(name, category=locale.LC_ALL): old_name = locale.getlocale(category) if None not in old_name: old_name = '.'.join(old_name) if isinstance(name, types.UnicodeType): name = str(name) if old_name != name: locale.setlocale(category, name) rows.fields.SHOULD_NOT_USE_LOCALE = False try: yield finally: if old_name != name: locale.setlocale(category, old_name) rows.fields.SHOULD_NOT_USE_LOCALE = True rows-0.1.1/rows/operations.py000066400000000000000000000046421257211624100162410ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals from collections import OrderedDict from rows.table import Table def join(keys, tables): """Merge a list of `Table` objects using `keys` to group rows""" # Make new (merged) Table fields fields = OrderedDict() map(lambda table: fields.update(table.fields), tables) # TODO: may raise an error if a same field is different in some tables # Check if all keys are inside merged Table's fields fields_keys = set(fields.keys()) for key in keys: if key not in fields_keys: raise ValueError('Invalid key: "{}"'.format(key)) # Group rows by key, without missing ordering none_fields = lambda: OrderedDict({field: None for field in fields.keys()}) data = OrderedDict() for table in tables: for row in table: row_key = tuple([getattr(row, key) for key in keys]) if row_key not in data: data[row_key] = none_fields() data[row_key].update(row._asdict()) merged = Table(fields=fields) merged.extend(data.values()) return merged def transform(fields, function, *tables): "Return a new table based on other tables and a transformation function" new_table = Table(fields=fields) for table in tables: map(new_table.append, filter(bool, map(lambda row: function(row, table), table))) return new_table def serialize(table, *args, **kwargs): fields = table.fields fields_items = fields.items() for row in table: yield [field_type.serialize(getattr(row, field_name), *args, **kwargs) for field_name, field_type in fields_items] rows-0.1.1/rows/plugins/000077500000000000000000000000001257211624100151575ustar00rootroot00000000000000rows-0.1.1/rows/plugins/__init__.py000066400000000000000000000000001257211624100172560ustar00rootroot00000000000000rows-0.1.1/rows/plugins/csv.py000066400000000000000000000036611257211624100163320ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import unicodecsv from rows.operations import serialize from rows.utils import create_table, get_filename_and_fobj def import_from_csv(filename_or_fobj, encoding='utf-8', delimiter=',', quotechar='"', *args, **kwargs): 'Import data from a CSV file' filename, fobj = get_filename_and_fobj(filename_or_fobj) kwargs['encoding'] = encoding csv_reader = unicodecsv.reader(fobj, encoding=encoding, delimiter=str(delimiter), quotechar=str(quotechar)) meta = {'imported_from': 'csv', 'filename': filename,} return create_table(csv_reader, meta=meta, *args, **kwargs) def export_to_csv(table, filename_or_fobj, encoding='utf-8'): # TODO: will work only if table.fields is OrderedDict # TODO: should use fobj? What about creating a method like json.dumps? filename, fobj = get_filename_and_fobj(filename_or_fobj, mode='w') csv_writer = unicodecsv.writer(fobj, encoding=encoding) csv_writer.writerow(table.fields.keys()) for row in serialize(table, encoding=encoding): csv_writer.writerow(row) fobj.flush() return fobj rows-0.1.1/rows/plugins/html.py000066400000000000000000000076321257211624100165050ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import HTMLParser from lxml.html import document_fromstring from lxml.etree import tostring as to_string, strip_tags from rows.operations import serialize from rows.utils import create_table, get_filename_and_fobj html_parser = HTMLParser.HTMLParser() def _get_content(element): content = to_string(element) content = content[content.find('>') + 1:content.rfind('<')].strip() return html_parser.unescape(content) def import_from_html(filename_or_fobj, encoding='utf-8', index=0, ignore_colspan=True, preserve_html=False, row_tag='tr', column_tag='td|th', *args, **kwargs): # TODO: unescape before returning: html_parser.unescape(html) # TODO: lxml -> unicode? filename, fobj = get_filename_and_fobj(filename_or_fobj) kwargs['encoding'] = encoding html = fobj.read().decode(encoding) html_tree = document_fromstring(html) tables = html_tree.xpath('//table') table = tables[index] strip_tags(table, 'thead') strip_tags(table, 'tbody') row_elements = table.xpath(row_tag) if not preserve_html: table_rows = [[value_element.text_content().strip() for value_element in row.xpath(column_tag)] for row in row_elements] else: table_rows = [[_get_content(value_element) for value_element in row.xpath(column_tag)] for row in row_elements] max_columns = max(len(row) for row in table_rows) if ignore_colspan: table_rows = filter(lambda row: len(row) == max_columns, table_rows) meta = {'imported_from': 'html', 'filename': filename,} return create_table(table_rows, meta=meta, *args, **kwargs) def export_to_html(table, filename_or_fobj=None, encoding='utf-8'): fields = table.fields.keys() result = ['
title firstname middlename lastname name_suffix nickname
\n\n', ' \n', ' \n'] header = [' \n'.format(field) for field in fields] result.extend(header) result.extend([' \n', ' \n', '\n', ' \n', '\n']) for index, row in enumerate(serialize(table, encoding=encoding), start=1): css_class = 'odd' if index % 2 == 1 else 'even' result.append(' \n'.format(css_class)) for value in row: result.extend([' \n']) result.append(' \n\n') result.append(' \n\n
{}
', value, '
\n') new_result = [value.encode(encoding) if isinstance(value, unicode) else value for value in result] html = ''.encode(encoding).join(new_result) if filename_or_fobj is not None: filename, fobj = get_filename_and_fobj(filename_or_fobj, mode='w') fobj.write(html) fobj.flush() return fobj else: return html def tag_to_dict(html): element = document_fromstring(html).xpath('//html/body/child::*')[0] attributes = dict(element.attrib) attributes['text'] = element.text_content() return attributes def tag_text(html): element = document_fromstring(html).xpath('//html/body/child::*')[0] return element.text_content() rows-0.1.1/rows/plugins/txt.py000066400000000000000000000046051257211624100163550ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals from rows.operations import serialize from rows.utils import get_filename_and_fobj DASH, PLUS, PIPE = '-', '+', '|' def _max_column_sizes(table, encoding, *args, **kwargs): header = table.fields.keys() max_sizes = {field_name: len(field_name) for field_name in header} for row in serialize(table, encoding=encoding, *args, **kwargs): for field_name, value in zip(header, row): length = len(value) if max_sizes[field_name] < length: max_sizes[field_name] = length return max_sizes def export_to_txt(table, filename_or_fobj, encoding='utf-8', *args, **kwargs): # TODO: will work only if table.fields is OrderedDict # TODO: should use fobj? What about creating a method like json.dumps? filename, fobj = get_filename_and_fobj(filename_or_fobj, mode='w') max_sizes = _max_column_sizes(table, encoding, *args, **kwargs) fields = table.fields.keys() dashes = [DASH * (max_sizes[field] + 2) for field in fields] header = [field.center(max_sizes[field]) for field in fields] header = '{} {} {}'.format(PIPE, ' {} '.format(PIPE).join(header), PIPE) split_line = PLUS + PLUS.join(dashes) + PLUS result = [split_line, header, split_line] for row in serialize(table): values = [value.rjust(max_sizes[field_name]) for field_name, value in zip(fields, row)] row_data = ' {} '.format(PIPE).join(values) result.append('{} {} {}'.format(PIPE, row_data, PIPE)) result.extend([split_line, '\n']) data = '\n'.join(result).encode(encoding) fobj.write(data) fobj.flush() return fobj rows-0.1.1/rows/plugins/xls.py000066400000000000000000000112771257211624100163470ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import datetime import xlrd import xlwt import rows.fields as fields from rows.utils import create_table, get_filename_and_fobj CELL_TYPES = {xlrd.XL_CELL_BLANK: fields.ByteField, xlrd.XL_CELL_DATE: fields.DatetimeField, xlrd.XL_CELL_ERROR: None, xlrd.XL_CELL_TEXT: fields.UnicodeField, xlrd.XL_CELL_BOOLEAN: fields.BoolField, xlrd.XL_CELL_EMPTY: None, xlrd.XL_CELL_NUMBER: fields.FloatField,} def cell_value(sheet, row, col): try: cell = sheet.cell(row, col) except IndexError: return None field_type = CELL_TYPES[cell.ctype] if field_type is None: return None # TODO: this approach will not work if using locale value = sheet.cell_value(row, col) if field_type is fields.DatetimeField: time_tuple = xlrd.xldate_as_tuple(value, sheet.book.datemode) value = field_type.serialize(datetime.datetime(*time_tuple)) return value.split('T00:00:00')[0] else: book = sheet.book xf = book.xf_list[cell.xf_index] fmt = book.format_map[xf.format_key] if fmt.format_str.endswith('%'): return '{}%'.format(cell.value * 100) elif type(value) == float and int(value) == value: return int(value) else: return value def import_from_xls(filename_or_fobj, sheet_name=None, sheet_index=0, start_row=0, start_column=0, *args, **kwargs): filename, _ = get_filename_and_fobj(filename_or_fobj) book = xlrd.open_workbook(filename, formatting_info=True) if sheet_name is not None: sheet = book.sheet_by_name(sheet_name) else: sheet = book.sheet_by_index(sheet_index) # TODO: may re-use Excel data types # Get field names # TODO: may use sheet.col_values or even sheet.ncols column_count = 0 header = [] column_value = cell_value(sheet, start_row, start_column + column_count) while column_value: header.append(column_value) column_count += 1 column_value = cell_value(sheet, start_row, start_column + column_count) # Get sheet rows # TODO: may use sheel.col_slice or even sheet.nrows table_rows = [] row_count = 0 start_row += 1 cell_is_empty = False while not cell_is_empty: row = [cell_value(sheet, start_row + row_count, start_column + column_index) for column_index in range(column_count)] cell_is_empty = not any(row) if not cell_is_empty: table_rows.append(row) row_count += 1 meta = {'imported_from': 'xls', 'filename': filename,} return create_table([header] + table_rows, meta=meta, *args, **kwargs) # TODO: add more formatting styles for other types such as currency # TODO: styles may be influenced by locale FORMATTING_STYLES = { fields.DateField: xlwt.easyxf(num_format_str='yyyy-mm-dd'), fields.DatetimeField: xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss'), fields.PercentField: xlwt.easyxf(num_format_str='0.00%'),} def export_to_xls(table, filename_or_fobj, sheet_name='Sheet1'): filename, fobj = get_filename_and_fobj(filename_or_fobj, mode='wb') work_book = xlwt.Workbook() sheet = work_book.add_sheet(sheet_name) fields = [(index, field_name) for index, field_name in enumerate(table.fields)] for index, field_name in fields: sheet.write(0, index, field_name) for row_index, row in enumerate(table, start=1): for column_index, field_name in fields: value = getattr(row, field_name) field_type = table.fields[field_name] data = {} if field_type in FORMATTING_STYLES: data['style'] = FORMATTING_STYLES[field_type] sheet.write(row_index, column_index, value, **data) work_book.save(fobj) fobj.flush() return fobj rows-0.1.1/rows/table.py000066400000000000000000000066721257211624100151520ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals from collections import MutableSequence, namedtuple, OrderedDict from operator import itemgetter import rows.fields as fields class Table(MutableSequence): def __init__(self, fields, meta=None): # TODO: should we really use OrderedDict here? # TODO: should use slug on each field name automatically or inside each # plugin? self.fields = OrderedDict(fields) self.field_names = self.fields.keys() self.field_types = self.fields.values() # TODO: should be able to customize row return type (namedtuple, dict # etc.) self.Row = namedtuple('Row', self.field_names) self._rows = [] self.meta = dict(meta) if meta is not None else {} def _make_row(self, row): # TODO: should be able to customize row type (namedtuple, dict etc.) return [field_type.deserialize(row.get(field_name, None)) for field_name, field_type in self.fields.items()] def append(self, row): """Add a row to the table. Should be a dict""" self._rows.append(self._make_row(row)) def __len__(self): return len(self._rows) def __getitem__(self, key): if isinstance(key, int): return self.Row(*self._rows[key]) elif isinstance(key, slice): return [self.Row(*row) for row in self._rows[key]] else: raise ValueError('Type not recognized: {}'.format(type(key))) def __setitem__(self, key, value): self._rows[key] = self._make_row(value) def __delitem__(self, key): del self._rows[key] def insert(self, index, row): self._rows.insert(index, self._make_row(row)) def __radd__(self, other): if other == 0: return self raise ValueError() # TODO: fix "table += other" def __add__(self, other): if other == 0: return self if type(self) != type(other) or self.fields != other.fields: raise ValueError('Tables have incompatible fields') table = Table(fields=self.fields) map(lambda row: table.append(row._asdict()), self) map(lambda row: table.append(row._asdict()), other) return table def order_by(self, key): # TODO: implement locale # TODO: implement for more than one key reverse = False if key.startswith('-'): key = key[1:] reverse = True field_names = self.fields.keys() if key not in field_names: raise ValueError('Field "{}" does not exist'.format(key)) key_index = field_names.index(key) self._rows.sort(key=itemgetter(key_index), reverse=reverse) rows-0.1.1/rows/utils.py000066400000000000000000000135601257211624100152150ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import collections import os import tempfile from unicodedata import normalize import requests import rows from rows.fields import detect_types from rows.table import Table # TODO: create functions to serialize/deserialize data SLUG_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_' def slug(text, encoding=None, separator='_', permitted_chars=SLUG_CHARS, replace_with_separator=' -_'): if isinstance(text, str): text = text.decode(encoding or 'ascii') clean_text = text.strip() for char in replace_with_separator: clean_text = clean_text.replace(char, separator) double_separator = separator + separator while double_separator in clean_text: clean_text = clean_text.replace(double_separator, separator) ascii_text = normalize('NFKD', clean_text).encode('ascii', 'ignore') strict_text = [x for x in ascii_text if x in permitted_chars] text = ''.join(strict_text).lower() if text.startswith(separator): text = text[len(separator):] if text.endswith(separator): text = text[:-len(separator)] return text def ipartition(iterable, n): if not isinstance(iterable, collections.Iterator): iterator = iter(iterable) else: iterator = iterable finished = False while not finished: data = [] for i in range(n): try: data.append(iterator.next()) except StopIteration: finished = True break yield data def make_header(data): header = [slug(field_name).lower() for field_name in data] return [field_name if field_name else 'field_{}'.format(index) for index, field_name in enumerate(header)] def create_table(data, meta=None, force_headers=None, fields=None, skip_header=True, *args, **kwargs): # TODO: add auto_detect_types=True parameter table_rows = list(data) if fields is None: if force_headers is None: header = make_header(table_rows[0]) table_rows = table_rows[1:] else: header = force_headers fields = detect_types(header, table_rows, *args, **kwargs) else: if skip_header: table_rows = table_rows[1:] header = make_header(fields.keys()) assert type(fields) is collections.OrderedDict fields = {field_name: fields[key] for field_name, key in zip(header, fields)} else: header = make_header(fields.keys()) # TODO: may reuse max_columns from html max_columns = max(len(row) for row in table_rows) assert len(fields) == max_columns # TODO: put this inside Table.__init__ table = Table(fields=fields, meta=meta) for row in table_rows: table.append({field_name: value for field_name, value in zip(header, row)}) return table def get_filename_and_fobj(filename_or_fobj, mode='r', dont_open=False): if getattr(filename_or_fobj, 'read', None) is not None: fobj = filename_or_fobj filename = getattr(fobj, 'name', None) else: fobj = open(filename_or_fobj, mode=mode) if not dont_open else None filename = filename_or_fobj return filename, fobj def download_file(uri): response = requests.get(uri) content = response.content # TODO: try to guess with uri.split('/')[-1].split('.')[-1].lower() try: content_type = response.headers['content-type'] plugin_name = content_type.split('/')[-1] except (KeyError, IndexError): try: plugin_name = uri.split('/')[-1].split('.')[-1].lower() except IndexError: raise RuntimeError('Could not identify file type.') tmp = tempfile.NamedTemporaryFile() filename = '{}.{}'.format(tmp.name, plugin_name) tmp.close() with open(filename, 'wb') as fobj: fobj.write(content) return filename def get_uri_information(uri): if uri.startswith('http://') or uri.startswith('https://'): should_delete = True filename = download_file(uri) else: should_delete = False filename = uri plugin_name = filename.split('.')[-1].lower() if plugin_name == 'htm': plugin_name = 'html' elif plugin_name == 'text': plugin_name = 'txt' return should_delete, filename, plugin_name def import_from_uri(uri): # TODO: support '-' also should_delete, filename, plugin_name = get_uri_information(uri) try: import_function = getattr(rows, 'import_from_{}'.format(plugin_name)) except AttributeError: raise ValueError('Plugin (import) "{}" not found'.format(plugin_name)) with open(filename) as fobj: table = import_function(fobj) if should_delete: os.unlink(filename) return table def export_to_uri(uri, table): # TODO: support '-' also plugin_name = uri.split('.')[-1].lower() try: export_function = getattr(rows, 'export_to_{}'.format(plugin_name)) except AttributeError: raise ValueError('Plugin (export) "{}" not found'.format(plugin_name)) export_function(table, uri) rows-0.1.1/setup.py000066400000000000000000000024511257211624100142200ustar00rootroot00000000000000# coding: utf-8 from setuptools import setup setup(name='rows', description='Import and export tabular data easily with Python', long_description='', version='0.1.1', author=u'Álvaro Justen', author_email='alvarojusten@gmail.com', url='https://github.com/turicas/rows/', packages=['rows', 'rows.plugins'], install_requires=['unicodecsv', 'click', 'requests'], extras_require = { 'csv': ['unicodecsv'], 'html': ['lxml'], # apt: libxslt-dev libxml2-dev 'cli': ['click', 'requests'], 'xls': ['xlrd', 'xlwt'], 'all': ['unicodecsv', 'lxml', 'click', 'requests', 'xlrd', 'xlwt'], }, keywords=['tabular', 'table', 'csv', 'xls', 'html', 'rows'], entry_points = { 'console_scripts': [ 'rows = rows.cli:cli', ], }, classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', ] ) rows-0.1.1/tests/000077500000000000000000000000001257211624100136465ustar00rootroot00000000000000rows-0.1.1/tests/data/000077500000000000000000000000001257211624100145575ustar00rootroot00000000000000rows-0.1.1/tests/data/all-field-types.csv000066400000000000000000000010131257211624100202620ustar00rootroot00000000000000bool_column,integer_column,float_column,decimal_column,percent_column,date_column,datetime_column,unicode_column,null_column 1,1,3.141592,3.141592,1%,2015-01-01,2015-08-18T15:10:00,Álvaro, 0,2,1.234,1.234,11.69%,1999-02-03,1999-02-03T00:01:02,àáãâä¹²³,- true,3,4.56,4.56,12%,2050-01-02,2050-01-02T23:45:31,éèẽêë,null false,4,7.89,7.89,13.64%,2015-08-18,2015-08-18T22:21:33,~~~~,nil yes,5,9.87,9.87,13.14%,2015-03-04,2015-03-04T16:00:01,álvaro,none no,6,1.2345,1.2345,2%,2015-05-06,2015-05-06T12:01:02,test, rows-0.1.1/tests/data/all-field-types.html000066400000000000000000000042131257211624100204400ustar00rootroot00000000000000
bool_column integer_column float_column decimal_column percent_column date_column datetime_column unicode_column null_column
true 1 3.141592 3.141592 1% 2015-01-01 2015-08-18T15:10:00 Álvaro
false 2 1.234 1.234 11.69% 1999-02-03 1999-02-03T00:01:02 àáãâä¹²³ -
true 3 4.56 4.56 12% 2050-01-02 2050-01-02T23:45:31 éèẽêë null
false 4 7.89 7.89 13.64% 2015-08-18 2015-08-18T22:21:33 ~~~~ nil
true 5 9.87 9.87 13.14% 2015-03-04 2015-03-04T16:00:01 álvaro none
false 6 1.2345 1.2345 2% 2015-05-06 2015-05-06T12:01:02 test
rows-0.1.1/tests/data/all-field-types.txt000066400000000000000000000027431257211624100203210ustar00rootroot00000000000000+-------------+----------------+--------------+----------------+----------------+-------------+---------------------+----------------+-------------+ | bool_column | integer_column | float_column | decimal_column | percent_column | date_column | datetime_column | unicode_column | null_column | +-------------+----------------+--------------+----------------+----------------+-------------+---------------------+----------------+-------------+ | true | 1 | 3.141592 | 3.141592 | 1% | 2015-01-01 | 2015-08-18T15:10:00 | Álvaro | | | false | 2 | 1.234 | 1.234 | 11.69% | 1999-02-03 | 1999-02-03T00:01:02 | àáãâä¹²³ | - | | true | 3 | 4.56 | 4.56 | 12% | 2050-01-02 | 2050-01-02T23:45:31 | éèẽêë | null | | false | 4 | 7.89 | 7.89 | 13.64% | 2015-08-18 | 2015-08-18T22:21:33 | ~~~~ | nil | | true | 5 | 9.87 | 9.87 | 13.14% | 2015-03-04 | 2015-03-04T16:00:01 | álvaro | none | | false | 6 | 1.2345 | 1.2345 | 2% | 2015-05-06 | 2015-05-06T12:01:02 | test | | +-------------+----------------+--------------+----------------+----------------+-------------+---------------------+----------------+-------------+ rows-0.1.1/tests/data/all-field-types.xls000066400000000000000000000130001257211624100202740ustar00rootroot00000000000000ࡱ>    \pNone Ba=c@=Z?N*8X"1Arial1Arial1Arial1Arial1Arial1Arial1Arial1Arial1Arial1Arial General yyyy-mm-ddyyyy-mm-dd hh:mm:ss                        `NSheet1 bool_columninteger_column float_columndecimal_columnpercent_column date_columndatetime_columnunicode_column null_columnlvaro乲-null~~~~nillvarononetest    dMbP?_%  *+&P&F&333333?'333333?(Q?)Gz?" d,,??c           ~ z! @z! @V98T@   ~  X9v?X9v?(?~ 5@@    $##3X@    W W R!u?~ ]@   ooX?~ NmUu@   ~ n?n? JP@ >@ Root EntryWorkbookrows-0.1.1/tests/data/colspan-table.html000066400000000000000000000004071257211624100201720ustar00rootroot00000000000000
huge title
field1 field2
row1field1 row1field2
row2field1 row2field2
rows-0.1.1/tests/data/ibge-censo.html000066400000000000000000000672161257211624100174740ustar00rootroot00000000000000
RJ Angra dos Reis 169.511
RJ Aperibé 10.213
RJ Araruama 112.008
RJ Areal 11.423
RJ Armação dos Búzios 27.560
RJ Arraial do Cabo 27.715
RJ Barra do Piraí 94.778
RJ Barra Mansa 177.813
RJ Belford Roxo 469.332
RJ Bom Jardim 25.333
RJ Bom Jesus do Itabapoana 35.411
RJ Cabo Frio 186.227
RJ Cachoeiras de Macacu 54.273
RJ Cambuci 14.827
RJ Campos dos Goytacazes 463.731
RJ Cantagalo 19.830
RJ Carapebus 13.359
RJ Cardoso Moreira 12.600
RJ Carmo 17.434
RJ Casimiro de Abreu 35.347
RJ Comendador Levy Gasparian 8.180
RJ Conceição de Macabu 21.211
RJ Cordeiro 20.430
RJ Duas Barras 10.930
RJ Duque de Caxias 855.048
RJ Engenheiro Paulo de Frontin 13.237
RJ Guapimirim 51.483
RJ Iguaba Grande 22.851
RJ Itaboraí 218.008
RJ Itaguaí 109.091
RJ Italva 14.063
RJ Itaocara 22.899
RJ Itaperuna 95.841
RJ Itatiaia 28.783
RJ Japeri 95.492
RJ Laje do Muriaé 7.487
RJ Macaé 206.728
RJ Macuco 5.269
RJ Magé 227.322
RJ Mangaratiba 36.456
RJ Maricá 127.461
RJ Mendes 17.935
RJ Mesquita 168.376
RJ Miguel Pereira 24.642
RJ Miracema 26.843
RJ Natividade 15.082
RJ Nilópolis 157.425
RJ Niterói 487.562
RJ Nova Friburgo 182.082
RJ Nova Iguaçu 796.257
RJ Paracambi 47.124
RJ Paraíba do Sul 41.084
RJ Paraty 37.533
RJ Paty do Alferes 26.359
RJ Petrópolis 295.917
RJ Pinheiral 22.719
RJ Piraí 26.314
RJ Porciúncula 17.760
RJ Porto Real 16.592
RJ Quatis 12.793
RJ Queimados 137.962
RJ Quissamã 20.242
RJ Resende 119.769
RJ Rio Bonito 55.551
RJ Rio Claro 17.425
RJ Rio das Flores 8.561
RJ Rio das Ostras 105.676
RJ Rio de Janeiro 6.320.446
RJ Santa Maria Madalena 10.321
RJ Santo Antônio de Pádua 40.589
RJ São Fidélis 37.543
RJ São Francisco de Itabapoana 41.354
RJ São Gonçalo 999.728
RJ São João da Barra 32.747
RJ São João de Meriti 458.673
RJ São José de Ubá 7.003
RJ São José do Vale do Rio Preto 20.251
RJ São Pedro da Aldeia 87.875
RJ São Sebastião do Alto 8.895
RJ Sapucaia 17.525
RJ Saquarema 74.234
RJ Seropédica 78.186
RJ Silva Jardim 21.349
RJ Sumidouro 14.900
RJ Tanguá 30.732
RJ Teresópolis 163.746
RJ Trajano de Moraes 10.289
RJ Três Rios 77.432
RJ Valença 71.843
RJ Varre-Sai 9.475
RJ Vassouras 34.410
RJ Volta Redonda 257.803
rows-0.1.1/tests/data/merged.csv000066400000000000000000000001421257211624100165340ustar00rootroot00000000000000id,username,birthday,gender 1,turicas,1987-04-29,M 2,abc,,F 3,def,2000-01-01,F 4,qwe,1999-12-31,F rows-0.1.1/tests/data/nested-table.html000066400000000000000000000022271257211624100200170ustar00rootroot00000000000000
t0,0r0c0 t0,0r0c1 t0,0r0c2
t0,0r1c0 t0,0r1c1 t0,0r1c2
t0,0r2c0
t0,1r0c0 t0,1r0c1
t0,1r1c0 t0,1r1c1
t0,1r2c0 t0,1r2c1
t0,2r0c0 t0,2r0c1
t0,2r1c0 t0,2r1c1
t0,1r3c1
t0,1r4c0 t0,1r4c1
t0,1r5c0 t0,1r5c1
t0,0r2c2
t0,0r3c0 t0,0r3c1 t0,0r3c2
rows-0.1.1/tests/data/simple-table.html000066400000000000000000000005121257211624100200210ustar00rootroot00000000000000
t0r0c0 t0r0c1
t0r1c0 t0r1c1
t1r0c0 t1r0c1
t1r1c0 t1r1c1
t1r2c0 t1r2c1
rows-0.1.1/tests/data/table-thead-tbody.html000066400000000000000000000003141257211624100207340ustar00rootroot00000000000000
t1 t2
456 123
qqq aaa
rows-0.1.1/tests/data/table-with-sections.html000066400000000000000000000024631257211624100213370ustar00rootroot00000000000000
t2r0c0 t2r0c1
t2r0c0 t2r0c1
t2r1c0 t2r1c1
t2r2c0 t2r2c1
id username name signup_date
1 turicas Álvaro Justen 2014-04-01
2 test Test User 2014-04-02
3 example Example User 2014-04-03
4 python Python Heavy User 2014-04-04
5 erlang Erlang User 2014-04-05
rows-0.1.1/tests/data/to-merge-1.csv000066400000000000000000000000421257211624100171450ustar00rootroot00000000000000id,username 1,turicas 2,abc 3,def rows-0.1.1/tests/data/to-merge-2.csv000066400000000000000000000001141257211624100171460ustar00rootroot00000000000000id,username,birthday 1,turicas,1987-04-29 3,def,2000-01-01 4,qwe,1999-12-31 rows-0.1.1/tests/data/to-merge-3.csv000066400000000000000000000000671257211624100171560ustar00rootroot00000000000000id,username,gender 1,turicas,M 2,abc,F 3,def,F 4,qwe,F rows-0.1.1/tests/tests_cli.py000066400000000000000000000016221257211624100162120ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import unittest import rows.cli as cli class CliTestCase(unittest.TestCase): # TODO: test everything pass rows-0.1.1/tests/tests_fields.py000066400000000000000000000373551257211624100167250ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import collections import datetime import unittest import types from decimal import Decimal import rows import platform from rows import fields if platform.system() == 'Windows': locale_name = str('ptb_bra') else: locale_name = 'pt_BR.UTF-8' class FieldsTestCase(unittest.TestCase): def test_Field(self): self.assertIs(fields.Field.TYPE, types.NoneType) self.assertIs(fields.Field.deserialize(None), None) self.assertEqual(fields.Field.deserialize('Álvaro'), 'Álvaro') self.assertEqual(fields.Field.serialize(None), '') self.assertIs(type(fields.Field.serialize(None)), types.UnicodeType) self.assertEqual(fields.Field.serialize('Álvaro'), 'Álvaro') self.assertIs(type(fields.Field.serialize('Álvaro')), types.UnicodeType) def test_ByteField(self): serialized = 'Álvaro'.encode('utf-8') self.assertIs(fields.ByteField.TYPE, types.StringType) self.assertIs(fields.ByteField.deserialize(None), None) self.assertEqual(fields.ByteField.deserialize(serialized), serialized) self.assertIs(type(fields.ByteField.deserialize(serialized)), types.StringType) self.assertEqual(fields.ByteField.serialize(None), '') self.assertIs(type(fields.ByteField.serialize(None)), types.StringType) self.assertEqual(fields.ByteField.serialize(serialized), serialized) self.assertIs(type(fields.ByteField.serialize(serialized)), types.StringType) def test_BoolField(self): self.assertIs(fields.BoolField.TYPE, bool) self.assertEqual(fields.BoolField.serialize(None), '') self.assertIs(type(fields.BoolField.serialize(None)), types.UnicodeType) self.assertIs(type(fields.BoolField.deserialize('true')), fields.BoolField.TYPE) self.assertIs(fields.BoolField.deserialize('0'), False) self.assertIs(fields.BoolField.deserialize('false'), False) self.assertIs(fields.BoolField.deserialize('no'), False) self.assertIs(fields.BoolField.deserialize(None), None) self.assertIs(fields.BoolField.deserialize(True), True) self.assertIs(fields.BoolField.deserialize(False), False) self.assertEqual(fields.BoolField.serialize(False), 'false') self.assertIs(type(fields.BoolField.serialize(False)), types.UnicodeType) self.assertIs(fields.BoolField.deserialize('1'), True) self.assertIs(fields.BoolField.deserialize(1), True) self.assertIs(fields.BoolField.deserialize('true'), True) self.assertIs(fields.BoolField.deserialize('yes'), True) self.assertEqual(fields.BoolField.serialize(True), 'true') self.assertIs(type(fields.BoolField.serialize(True)), types.UnicodeType) def test_IntegerField(self): self.assertIs(fields.IntegerField.TYPE, int) self.assertEqual(fields.IntegerField.serialize(None), '') self.assertIs(type(fields.IntegerField.serialize(None)), types.UnicodeType) self.assertIs(type(fields.IntegerField.deserialize('42')), fields.IntegerField.TYPE) self.assertEqual(fields.IntegerField.deserialize('42'), 42) self.assertEqual(fields.IntegerField.deserialize(42), 42) self.assertEqual(fields.IntegerField.serialize(42), '42') self.assertIs(type(fields.IntegerField.serialize(42)), types.UnicodeType) self.assertEqual(fields.IntegerField.deserialize(None), None) with rows.locale_context(locale_name): self.assertEqual(fields.IntegerField.serialize(42000), '42000') self.assertIs(type(fields.IntegerField.serialize(42000)), types.UnicodeType) self.assertEqual(fields.IntegerField.serialize(42000, grouping=True), '42.000') self.assertEqual(fields.IntegerField.deserialize('42.000'), 42000) with self.assertRaises(ValueError): fields.IntegerField.deserialize(1.23) def test_FloatField(self): self.assertIs(fields.FloatField.TYPE, float) self.assertEqual(fields.FloatField.serialize(None), '') self.assertIs(type(fields.FloatField.serialize(None)), types.UnicodeType) self.assertIs(type(fields.FloatField.deserialize('42.0')), fields.FloatField.TYPE) self.assertEqual(fields.FloatField.deserialize('42.0'), 42.0) self.assertEqual(fields.FloatField.deserialize(42.0), 42.0) self.assertEqual(fields.FloatField.deserialize(42), 42.0) self.assertEqual(fields.FloatField.deserialize(None), None) self.assertEqual(fields.FloatField.serialize(42.0), '42.0') self.assertIs(type(fields.FloatField.serialize(42.0)), types.UnicodeType) with rows.locale_context(locale_name): self.assertEqual(fields.FloatField.serialize(42000.0), '42000,000000') self.assertIs(type(fields.FloatField.serialize(42000.0)), types.UnicodeType) self.assertEqual(fields.FloatField.serialize(42000, grouping=True), '42.000,000000') self.assertEqual(fields.FloatField.deserialize('42.000,00'), 42000.0) self.assertEqual(fields.FloatField.deserialize(42), 42.0) def test_DecimalField(self): deserialized = Decimal('42.010') self.assertIs(fields.DecimalField.TYPE, Decimal) self.assertEqual(fields.DecimalField.serialize(None), '') self.assertIs(type(fields.DecimalField.serialize(None)), types.UnicodeType) self.assertIs(type(fields.DecimalField.deserialize('42.0')), fields.DecimalField.TYPE) self.assertEqual(fields.DecimalField.deserialize('42.0'), Decimal('42.0')) self.assertEqual(fields.DecimalField.deserialize(deserialized), deserialized) self.assertEqual(fields.DecimalField.serialize(deserialized), '42.010') self.assertEqual(type(fields.DecimalField.serialize(deserialized)), types.UnicodeType) self.assertEqual(fields.DecimalField.deserialize('21.21657469231'), Decimal('21.21657469231')) self.assertEqual(fields.DecimalField.deserialize(None), None) with rows.locale_context(locale_name): self.assertEqual( types.UnicodeType, type(fields.DecimalField.serialize(deserialized)) ) self.assertEqual(fields.DecimalField.serialize(Decimal('4200')), '4200') self.assertEqual(fields.DecimalField.serialize(Decimal('42.0')), '42,0') self.assertEqual(fields.DecimalField.serialize(Decimal('42000.0')), '42000,0') self.assertEqual(fields.DecimalField.deserialize('42.000,00'), Decimal('42000.00')) self.assertEqual( fields.DecimalField.serialize( Decimal('42000.0'), grouping=True ), '42.000,0' ) def test_PercentField(self): deserialized = Decimal('0.42010') self.assertIs(fields.PercentField.TYPE, Decimal) self.assertIs(type(fields.PercentField.deserialize('42.0%')), fields.PercentField.TYPE) self.assertEqual(fields.PercentField.deserialize('42.0%'), Decimal('0.420')) self.assertEqual(fields.PercentField.deserialize(Decimal('0.420')), Decimal('0.420')) self.assertEqual(fields.PercentField.deserialize(deserialized), deserialized) self.assertEqual(fields.PercentField.deserialize(None), None) self.assertEqual(fields.PercentField.serialize(deserialized), '42.010%') self.assertEqual(type(fields.PercentField.serialize(deserialized)), types.UnicodeType) self.assertEqual(fields.PercentField.serialize(Decimal('42.010')), '4201.0%') self.assertEqual(fields.PercentField.serialize(Decimal('0.01')), '1%') with rows.locale_context(locale_name): self.assertEqual( type(fields.PercentField.serialize(deserialized)), types.UnicodeType ) self.assertEqual(fields.PercentField.serialize(Decimal('42.0')), '4200%') self.assertEqual(fields.PercentField.serialize(Decimal('42000.0')), '4200000%') self.assertEqual(fields.PercentField.deserialize('42.000,00%'), Decimal('420.0000')) self.assertEqual(fields.PercentField.serialize(Decimal('42000.00'), grouping=True), '4.200.000%') with self.assertRaises(ValueError): fields.PercentField.deserialize(42) def test_DateField(self): # TODO: test timezone-aware datetime.date serialized = types.StringType('2015-05-27') deserialized = datetime.date(2015, 5, 27) self.assertIs(fields.DateField.TYPE, datetime.date) self.assertEqual(fields.DateField.serialize(None), '') self.assertIs(type(fields.DateField.serialize(None)), types.UnicodeType) self.assertIs(type(fields.DateField.deserialize(serialized)), fields.DateField.TYPE) self.assertEqual(fields.DateField.deserialize(serialized), deserialized) self.assertEqual(fields.DateField.deserialize(deserialized), deserialized) self.assertEqual(fields.DateField.deserialize(None), None) self.assertEqual(fields.DateField.serialize(deserialized), serialized) self.assertIs(type(fields.DateField.serialize(deserialized)), types.UnicodeType) with self.assertRaises(ValueError): fields.DateField.deserialize(42) with self.assertRaises(ValueError): fields.DateField.deserialize(serialized + 'T00:00:00') def test_DatetimeField(self): # TODO: test timezone-aware datetime.date serialized = types.StringType('2015-05-27T01:02:03') self.assertIs(fields.DatetimeField.TYPE, datetime.datetime) deserialized = fields.DatetimeField.deserialize(serialized) self.assertIs(type(deserialized), fields.DatetimeField.TYPE) self.assertEqual(fields.DatetimeField.serialize(None), '') self.assertIs(type(fields.DatetimeField.serialize(None)), types.UnicodeType) value = datetime.datetime(2015, 5, 27, 1, 2, 3) self.assertEqual(fields.DatetimeField.deserialize(serialized), value) self.assertEqual(fields.DatetimeField.deserialize(deserialized), deserialized) self.assertEqual(fields.DatetimeField.deserialize(None), None) self.assertEqual(fields.DatetimeField.serialize(value), serialized) self.assertIs(type(fields.DatetimeField.serialize(value)), types.UnicodeType) with self.assertRaises(ValueError): fields.DatetimeField.deserialize(42) fields.DatetimeField.deserialize('2015-01-01') def test_UnicodeField(self): self.assertIs(fields.UnicodeField.TYPE, unicode) self.assertEqual(fields.UnicodeField.serialize(None), '') self.assertIs(type(fields.UnicodeField.serialize(None)), types.UnicodeType) self.assertIs(type(fields.UnicodeField.deserialize('test')), fields.UnicodeField.TYPE) self.assertEqual( fields.UnicodeField.deserialize( 'Álvaro'.encode('utf-8'), encoding='utf-8' ), 'Álvaro' ) self.assertEqual(fields.UnicodeField.deserialize('Álvaro'), 'Álvaro') self.assertIs(fields.UnicodeField.deserialize(None), None) self.assertEqual(fields.UnicodeField.serialize('Álvaro'), 'Álvaro') self.assertIs(type(fields.UnicodeField.serialize('Álvaro')), types.UnicodeType) class FieldUtilsTestCase(unittest.TestCase): maxDiff = None def setUp(self): with open('tests/data/all-field-types.csv') as fobj: lines = fobj.read().splitlines() lines = [line.split(','.encode('utf-8')) for line in lines] self.fields = lines[0] self.data = lines[1:] self.expected = {'bool_column': fields.BoolField, 'integer_column': fields.IntegerField, 'float_column': fields.FloatField, 'decimal_column': fields.FloatField, 'percent_column': fields.PercentField, 'date_column': fields.DateField, 'datetime_column': fields.DatetimeField, 'unicode_column': fields.UnicodeField, 'null_column': fields.ByteField, } def test_detect_types_utf8(self): result = fields.detect_types( self.fields, self.data, encoding='utf-8' ) self.assertEqual(type(result), collections.OrderedDict) self.assertEqual(result.keys(), self.fields) self.assertDictEqual(dict(result), self.expected) def test_detect_types_unicode(self): data = [[field.decode('utf-8') for field in row] for row in self.data] result = fields.detect_types(self.fields, data) self.assertDictEqual(dict(result), self.expected) class FieldsFunctionsTestCase(unittest.TestCase): def test_is_null(self): self.assertEqual(fields.is_null(None), True) self.assertEqual(fields.is_null(''), True) self.assertEqual(fields.is_null(' \t '), True) self.assertEqual(fields.is_null('null'), True) self.assertEqual(fields.is_null('nil'), True) self.assertEqual(fields.is_null('none'), True) self.assertEqual(fields.is_null('-'), True) self.assertEqual(fields.is_null('Álvaro'), False) self.assertEqual(fields.is_null('Álvaro'.encode('utf-8')), False) def test_as_string(self): self.assertEqual(fields.as_string(None), 'None') self.assertEqual(fields.as_string(42), '42') self.assertEqual(fields.as_string(3.141592), '3.141592') self.assertEqual(fields.as_string('Álvaro'), 'Álvaro') self.assertEqual(fields.as_string('Álvaro'.encode('utf-8')), 'Álvaro'.encode('utf-8')) rows-0.1.1/tests/tests_localization.py000066400000000000000000000027411257211624100201360ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import unittest import platform import rows import rows.fields from rows.localization import locale_context class LocalizationTestCase(unittest.TestCase): def test_locale_context_present_in_main_namespace(self): self.assertIn('locale_context', dir(rows)) self.assertIs(locale_context, rows.locale_context) def test_locale_context(self): self.assertTrue(rows.fields.SHOULD_NOT_USE_LOCALE) if platform.system() == 'Windows': name = str('ptb_bra') else: name = 'pt_BR.UTF-8' with locale_context(name): self.assertFalse(rows.fields.SHOULD_NOT_USE_LOCALE) self.assertTrue(rows.fields.SHOULD_NOT_USE_LOCALE) rows-0.1.1/tests/tests_operations.py000066400000000000000000000057441257211624100176370ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import unittest import rows import rows.operations import utils class OperationsTestCase(utils.RowsTestMixIn, unittest.TestCase): def test_join_imports(self): self.assertIs(rows.join, rows.operations.join) def test_join_feature(self): tables = [rows.import_from_csv('tests/data/to-merge-1.csv'), rows.import_from_csv('tests/data/to-merge-2.csv'), rows.import_from_csv('tests/data/to-merge-3.csv'),] merged = rows.join(keys=('id', 'username'), tables=tables) expected = rows.import_from_csv('tests/data/merged.csv') self.assert_table_equal(merged, expected) def test_transform_imports(self): self.assertIs(rows.transform, rows.operations.transform) def test_transform_feature(self): def transformation_function(row, table): if row.percent_column < 0.1269: return None # discard this row new = row._asdict() new['meta'] = ', '.join(['{} => {}'.format(key, value) for key, value in table._meta.items()]) return new fields = utils.table.fields.copy() fields.update({'meta': rows.fields.UnicodeField}) tables = [utils.table] * 3 result = rows.transform(fields, transformation_function, *tables) self.assertEqual(result.fields, fields) not_discarded = [transformation_function(row, utils.table) for row in utils.table] * 3 not_discarded = [row for row in not_discarded if row is not None] self.assertEqual(len(result), len(not_discarded)) for expected_row, row in zip(not_discarded, result): self.assertEqual(expected_row, dict(row._asdict())) def test_serialize_imports(self): self.assertIs(rows.serialize, rows.operations.serialize) def test_serialize_feature(self): result = rows.serialize(utils.table) header = utils.table.fields.values() for row, expected_row in zip(result, utils.table._rows): list_of_values = [field.serialize(value) for field, value in zip(header, expected_row)] self.assertEqual(list_of_values, row) rows-0.1.1/tests/tests_plugin_csv.py000066400000000000000000000051161257211624100176160ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import tempfile import unittest import rows import rows.plugins.csv import utils class PluginCsvTestCase(utils.RowsTestMixIn, unittest.TestCase): filename = 'tests/data/all-field-types.csv' encoding = 'utf-8' def test_imports(self): self.assertIs(rows.import_from_csv, rows.plugins.csv.import_from_csv) self.assertIs(rows.export_to_csv, rows.plugins.csv.export_to_csv) def test_import_from_csv_filename(self): table = rows.import_from_csv(self.filename, encoding=self.encoding) self.assert_table_equal(table, utils.table) expected_meta = {'imported_from': 'csv', 'filename': self.filename,} self.assertEqual(table.meta, expected_meta) def test_import_from_csv_fobj(self): # TODO: may test with codecs.open passing an encoding with open(self.filename) as fobj: table = rows.import_from_csv(fobj, encoding=self.encoding) self.assert_table_equal(table, utils.table) expected_meta = {'imported_from': 'csv', 'filename': self.filename,} self.assertEqual(table.meta, expected_meta) def test_export_to_csv_filename(self): # TODO: may test file contents temp = tempfile.NamedTemporaryFile(delete=False) self.files_to_delete.append(temp.name) rows.export_to_csv(utils.table, temp.name) table = rows.import_from_csv(temp.name) self.assert_table_equal(table, utils.table) def test_export_to_csv_fobj(self): # TODO: may test with codecs.open passing an encoding # TODO: may test file contents temp = tempfile.NamedTemporaryFile(delete=False) self.files_to_delete.append(temp.name) rows.export_to_csv(utils.table, temp.file) table = rows.import_from_csv(temp.name) self.assert_table_equal(table, utils.table) rows-0.1.1/tests/tests_plugin_html.py000066400000000000000000000227021257211624100177670ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import tempfile import unittest import rows import rows.plugins.html import utils # TODO: test unescape # TODO: test colspan # TODO: test rowspan # TODO: test more nested tables # URL = 'https://finance.yahoo.com/q;_ylt=At7WXTIEGzyrIHemoSMI7I.iuYdG;_ylu=X3oDMTBxdGVyNzJxBHNlYwNVSCAzIERlc2t0b3AgU2VhcmNoIDEx;_ylg=X3oDMTByaDM4cG9kBGxhbmcDZW4tVVMEcHQDMgR0ZXN0AzUxMjAxMw--;_ylv=3?s=GOOG&uhb=uhb2&type=2button&fr=uh3_finance_web_gs' # URL_2 = 'http://www.rio.rj.gov.br/dlstatic/10112/2147539/DLFE-237833.htm/paginanova2.0.0.0._B.htm' def cleanup_lines(lines): return [line.strip() for line in lines.strip().split('\n') if line.strip()] class PluginHtmlTestCase(utils.RowsTestMixIn, unittest.TestCase): filename = 'tests/data/all-field-types.html' encoding = 'utf-8' def test_imports(self): self.assertIs(rows.import_from_html, rows.plugins.html.import_from_html) self.assertIs(rows.export_to_html, rows.plugins.html.export_to_html) def test_import_from_html_filename(self): table = rows.import_from_html(self.filename, encoding=self.encoding) self.assert_table_equal(table, utils.table) expected_meta = {'imported_from': 'html', 'filename': self.filename,} self.assertEqual(table.meta, expected_meta) def test_import_from_html_fobj(self): # TODO: may test with codecs.open passing an encoding with open(self.filename) as fobj: table = rows.import_from_html(fobj, encoding=self.encoding) self.assert_table_equal(table, utils.table) expected_meta = {'imported_from': 'html', 'filename': self.filename,} self.assertEqual(table.meta, expected_meta) def test_export_to_html_filename(self): # TODO: may test file contents temp = tempfile.NamedTemporaryFile(delete=False) self.files_to_delete.append(temp.name) rows.export_to_html(utils.table, temp.name) table = rows.import_from_html(temp.name) self.assert_table_equal(table, utils.table) def test_export_to_html_fobj(self): # TODO: may test with codecs.open passing an encoding # TODO: may test file contents temp = tempfile.NamedTemporaryFile(delete=False) self.files_to_delete.append(temp.name) rows.export_to_html(utils.table, temp.file) table = rows.import_from_html(temp.name) self.assert_table_equal(table, utils.table) def test_export_to_html_none(self): # TODO: may test with codecs.open passing an encoding # TODO: may test file contents temp = tempfile.NamedTemporaryFile(delete=False) self.files_to_delete.append(temp.name) result = rows.export_to_html(utils.table) rows.export_to_html(utils.table, temp.file) temp.file.seek(0) self.assertEqual(temp.file.read(), result) def test_table_index(self): filename = 'tests/data/simple-table.html' fobj = open(filename) table_1 = rows.import_from_html(fobj) self.assertEqual(set(table_1.fields.keys()), set(['t0r0c0', 't0r0c1'])) self.assertEqual(len(table_1), 1) self.assertEqual(table_1[0].t0r0c0, 't0r1c0') self.assertEqual(table_1[0].t0r0c1, 't0r1c1') fobj.seek(0) table_2 = rows.import_from_html(fobj, index=1) self.assertEqual(set(table_2.fields.keys()), set(['t1r0c0', 't1r0c1'])) self.assertEqual(len(table_2), 2) self.assertEqual(table_2[0].t1r0c0, 't1r1c0') self.assertEqual(table_2[0].t1r0c1, 't1r1c1') self.assertEqual(table_2[1].t1r0c0, 't1r2c0') self.assertEqual(table_2[1].t1r0c1, 't1r2c1') def test_table_thead_tbody(self): filename = 'tests/data/table-thead-tbody.html' fobj = open(filename) table = rows.import_from_html(fobj) self.assertEqual(set(table.fields.keys()), set(['t1', 't2'])) self.assertEqual(len(table), 2) self.assertEqual(table[0].t1, '456') self.assertEqual(table[0].t2, '123') self.assertEqual(table[1].t1, 'qqq') self.assertEqual(table[1].t2, 'aaa') def test_nested_tables_outer(self): filename = 'tests/data/nested-table.html' fobj = open(filename) table = rows.import_from_html(fobj) self.assertEqual(set(table.fields.keys()), set(['t00r0c0', 't00r0c1', 't00r0c2'])) self.assertEqual(len(table), 3) self.assertEqual(table[0].t00r0c0, 't0,0r1c0') self.assertEqual(table[0].t00r0c1, 't0,0r1c1') self.assertEqual(table[0].t00r0c2, 't0,0r1c2') inner_table = ('t0,1r0c0 t0,1r0c1 t0,1r1c0 t0,1r1c1 t0,1r2c0 ' 't0,1r2c1 t0,2r0c0 t0,2r0c1 t0,2r1c0 t0,2r1c1 ' 't0,1r3c1 t0,1r4c0 t0,1r4c1 t0,1r5c0 t0,1r5c1').split() self.assertEqual(table[1].t00r0c0, 't0,0r2c0') self.assertEqual(cleanup_lines(table[1].t00r0c1), inner_table) self.assertEqual(table[1].t00r0c2, 't0,0r2c2') self.assertEqual(table[2].t00r0c0, 't0,0r3c0') self.assertEqual(table[2].t00r0c1, 't0,0r3c1') self.assertEqual(table[2].t00r0c2, 't0,0r3c2') def test_nested_tables_first_inner(self): filename = 'tests/data/nested-table.html' fobj = open(filename) table = rows.import_from_html(fobj, index=1) self.assertEqual(set(table.fields.keys()), set(['t01r0c0', 't01r0c1'])) self.assertEqual(len(table), 5) self.assertEqual(table[0].t01r0c0, 't0,1r1c0') self.assertEqual(table[0].t01r0c1, 't0,1r1c1') self.assertEqual(table[1].t01r0c0, 't0,1r2c0') self.assertEqual(table[1].t01r0c1, 't0,1r2c1') inner_table = 't0,2r0c0 t0,2r0c1 t0,2r1c0 t0,2r1c1'.split() self.assertEqual(cleanup_lines(table[2].t01r0c0), inner_table) self.assertEqual(table[2].t01r0c1, 't0,1r3c1') self.assertEqual(table[3].t01r0c0, 't0,1r4c0') self.assertEqual(table[3].t01r0c1, 't0,1r4c1') self.assertEqual(table[4].t01r0c0, 't0,1r5c0') self.assertEqual(table[4].t01r0c1, 't0,1r5c1') def test_nested_tables_second_inner(self): filename = 'tests/data/nested-table.html' fobj = open(filename) table = rows.import_from_html(fobj, index=2) self.assertEqual(set(table.fields.keys()), set(['t02r0c0', 't02r0c1'])) self.assertEqual(len(table), 1) self.assertEqual(table[0].t02r0c0, 't0,2r1c0') self.assertEqual(table[0].t02r0c1, 't0,2r1c1') def test_preserve_html(self): filename = 'tests/data/nested-table.html' fobj = open(filename) table = rows.import_from_html(fobj, preserve_html=True) expected_data = [ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '
t0,1r0c0 t0,1r0c1
t0,1r1c0 t0,1r1c1
t0,1r2c0 t0,1r2c1
', '', '', '', '', '', '', '', '', '', '
t0,2r0c0 t0,2r0c1
t0,2r1c0 t0,2r1c1
', '
t0,1r3c1
t0,1r4c0 t0,1r4c1
t0,1r5c0 t0,1r5c1
'] self.assertEqual(cleanup_lines(table[1].t00r0c1), expected_data) def test_ignore_colspan(self): filename = 'tests/data/colspan-table.html' fobj = open(filename) table = rows.import_from_html(fobj, ignore_colspan=True) self.assertEqual(set(table.fields.keys()), set(['field1', 'field2'])) self.assertEqual(len(table), 2) self.assertEqual(table[0].field1, 'row1field1') self.assertEqual(table[0].field2, 'row1field2') self.assertEqual(table[1].field1, 'row2field1') self.assertEqual(table[1].field2, 'row2field2') fobj = open(filename) with self.assertRaises(ValueError) as raises: table = rows.import_from_html(fobj, ignore_colspan=False) self.assertEqual(raises.exception.message, 'Number of fields differ') class PluginHtmlUtilsTestCase(unittest.TestCase): html = ' some text other' def test_tag_to_dict(self): result = rows.plugins.html.tag_to_dict(self.html) expected = {'text': ' some text ', 'class': 'some-class', 'href': 'some-url'} self.assertEqual(result, expected) def test_tag_text(self): result = rows.plugins.html.tag_text(self.html) expected = ' some text ' self.assertEqual(result, expected) rows-0.1.1/tests/tests_plugin_txt.py000066400000000000000000000032571257211624100176460ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import tempfile import unittest import rows import rows.plugins.txt import utils class PluginTxtTestCase(utils.RowsTestMixIn, unittest.TestCase): filename = 'tests/data/all-field-types.txt' encoding = 'utf-8' def test_imports(self): self.assertIs(rows.export_to_txt, rows.plugins.txt.export_to_txt) def test_export_to_txt_filename(self): temp = tempfile.NamedTemporaryFile(delete=False) self.files_to_delete.append(temp.name) rows.export_to_txt(utils.table, temp.name) self.assert_file_contents_equal(temp.name, self.filename) def test_export_to_txt_fobj(self): # TODO: may test with codecs.open passing an encoding temp = tempfile.NamedTemporaryFile(delete=False) self.files_to_delete.append(temp.name) rows.export_to_txt(utils.table, temp.file) self.assert_file_contents_equal(temp.name, self.filename) rows-0.1.1/tests/tests_plugin_xls.py000066400000000000000000000053271257211624100176350ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import datetime import tempfile import time import unittest import rows import rows.fields as fields import rows.plugins.xls import utils def date_to_datetime(value): return datetime.datetime.fromtimestamp(time.mktime(value.timetuple())) class PluginXlsTestCase(utils.RowsTestMixIn, unittest.TestCase): filename = 'tests/data/all-field-types.xls' def test_imports(self): self.assertIs(rows.import_from_xls, rows.plugins.xls.import_from_xls) self.assertIs(rows.export_to_xls, rows.plugins.xls.export_to_xls) def test_import_from_xls_filename(self): table = rows.import_from_xls(self.filename) self.assert_table_equal(table, utils.table) expected_meta = {'imported_from': 'xls', 'filename': self.filename,} self.assertEqual(table.meta, expected_meta) def test_import_from_xls_fobj(self): # TODO: may test with codecs.open passing an encoding with open(self.filename, 'rb') as fobj: table = rows.import_from_xls(fobj) self.assert_table_equal(table, utils.table) expected_meta = {'imported_from': 'xls', 'filename': self.filename,} self.assertEqual(table.meta, expected_meta) def test_export_to_xls_filename(self): # TODO: may test file contents temp = tempfile.NamedTemporaryFile(delete=False) self.files_to_delete.append(temp.name) rows.export_to_xls(utils.table, temp.name) table = rows.import_from_xls(temp.name) self.assert_table_equal(table, utils.table) def test_export_to_xls_fobj(self): # TODO: may test with codecs.open passing an encoding # TODO: may test file contents temp = tempfile.NamedTemporaryFile(delete=False, mode='wb') self.files_to_delete.append(temp.name) rows.export_to_xls(utils.table, temp.file) temp.file.close() table = rows.import_from_xls(temp.name) self.assert_table_equal(table, utils.table) rows-0.1.1/tests/tests_table.py000066400000000000000000000121621257211624100165330ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import datetime import unittest import rows import rows.fields as fields from rows.table import Table class TableTestCase(unittest.TestCase): def setUp(self): self.table = Table(fields={'name': rows.fields.UnicodeField, 'birthdate': rows.fields.DateField, }) self.first_row = {'name': u'Álvaro Justen', 'birthdate': datetime.date(1987, 4, 29)} self.table.append(self.first_row) self.table.append({'name': u'Somebody', 'birthdate': datetime.date(1990, 2, 1)}) self.table.append({'name': u'Douglas Adams', 'birthdate': '1952-03-11'}) def test_Table_is_present_on_main_namespace(self): self.assertIn('Table', dir(rows)) self.assertIs(Table, rows.Table) def test_table_iteration(self): # TODO: may test with all field types (using tests.utils.table) table_rows = [row for row in self.table] self.assertEqual(len(table_rows), 3) self.assertEqual(table_rows[0].name, u'Álvaro Justen') self.assertEqual(table_rows[0].birthdate, datetime.date(1987, 4, 29)) self.assertEqual(table_rows[1].name, u'Somebody') self.assertEqual(table_rows[1].birthdate, datetime.date(1990, 2, 1)) self.assertEqual(table_rows[2].name, u'Douglas Adams') self.assertEqual(table_rows[2].birthdate, datetime.date(1952, 3, 11)) def test_table_append_error(self): # TODO: may mock these validations and test only on *Field tests with self.assertRaises(ValueError) as context_manager: self.table.append({'name': 'Álvaro Justen'.encode('utf-8'), 'birthdate': '1987-04-29'}) self.assertEqual(type(context_manager.exception), UnicodeDecodeError) with self.assertRaises(ValueError) as context_manager: self.table.append({'name': u'Álvaro Justen', 'birthdate': 'WRONG'}) self.assertEqual(type(context_manager.exception), ValueError) self.assertIn('does not match format', context_manager.exception.message) def test_table_getitem_error(self): with self.assertRaises(ValueError) as context_manager: self.table['test'] def test_table_setitem(self): self.first_row['name'] = 'turicas' self.first_row['birthdate'] = datetime.date(2000, 1, 1) self.table[0] = self.first_row self.assertEqual(self.table[0].name, 'turicas') self.assertEqual(self.table[0].birthdate, datetime.date(2000, 1, 1)) def test_table_delitem(self): table_rows = [row for row in self.table] before = len(self.table) del self.table[0] after = len(self.table) self.assertEqual(after, before - 1) for row, expected_row in zip(self.table, table_rows[1:]): self.assertEqual(row, expected_row) def test_table_add(self): self.assertIs(self.table + 0, self.table) self.assertIs(0 + self.table, self.table) new_table = self.table + self.table self.assertEqual(new_table.fields, self.table.fields) self.assertEqual(len(new_table), 2 * len(self.table)) self.assertEqual(list(new_table), list(self.table) * 2) def test_table_add_error(self): with self.assertRaises(ValueError): self.table + 1 with self.assertRaises(ValueError): 1 + self.table def test_table_order_by(self): with self.assertRaises(ValueError): self.table.order_by('doesnt_exist') before = [row.birthdate for row in self.table] self.table.order_by('birthdate') after = [row.birthdate for row in self.table] self.assertNotEqual(before, after) self.assertEqual(sorted(before), after) self.table.order_by('-birthdate') final = [row.birthdate for row in self.table] self.assertEqual(final, list(reversed(after))) self.table.order_by('name') expected_rows = [ {'name': 'Douglas Adams', 'birthdate': datetime.date(1952, 3, 11)}, {'name': 'Somebody', 'birthdate': datetime.date(1990, 2, 1)}, {'name': 'Álvaro Justen', 'birthdate': datetime.date(1987, 4, 29)}] for expected_row, row in zip(expected_rows, self.table): self.assertEqual(expected_row, dict(row._asdict())) rows-0.1.1/tests/tests_utils.py000066400000000000000000000040711257211624100166040ustar00rootroot00000000000000# coding: utf-8 from __future__ import unicode_literals import types import unittest from collections import OrderedDict import rows.fields as fields from rows.utils import create_table, ipartition, slug class UtilsTestCase(unittest.TestCase): def test_slug(self): self.assertEqual(slug('Álvaro Justen'), 'alvaro_justen') self.assertEqual(slug("Moe's Bar"), 'moes_bar') self.assertEqual(slug("-----te-----st------"), 'te_st') def test_ipartition(self): iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = ipartition(iterable, 3) self.assertEqual(type(result), types.GeneratorType) self.assertEqual(list(result), [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]) def test_create_table_skip_header(self): field_types = OrderedDict([('integer', fields.IntegerField), ('string', fields.UnicodeField),]) data = [['1', 'Álvaro'], ['2', 'turicas'], ['3', 'Justen']] table_1 = create_table(data, fields=field_types, skip_header=True) table_2 = create_table(data, fields=field_types, skip_header=False) self.assertEqual(field_types, table_1.fields) self.assertEqual(table_1.fields, table_2.fields) self.assertEqual(len(table_1), 2) self.assertEqual(len(table_2), 3) first_row = {'integer': 1, 'string': 'Álvaro'} second_row = {'integer': 2, 'string': 'turicas'} third_row = {'integer': 3, 'string': 'Justen'} self.assertEqual(dict(table_1[0]._asdict()), second_row) self.assertEqual(dict(table_2[0]._asdict()), first_row) self.assertEqual(dict(table_1[1]._asdict()), third_row) self.assertEqual(dict(table_2[1]._asdict()), second_row) self.assertEqual(dict(table_2[2]._asdict()), third_row) # TODO: test make_header # TODO: test all features of create_table # TODO: test get_fobj_and_filename (BytesIO should return filename = None) # TODO: test download_file # TODO: test get_uri_information # TODO: test import_from_uri # TODO: test export_to_uri rows-0.1.1/tests/utils.py000066400000000000000000000113251257211624100153620ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014-2015 Álvaro Justen # # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import unicode_literals import datetime import os from collections import OrderedDict from decimal import Decimal import rows.fields as fields from rows.table import Table expected_fields = OrderedDict([('bool_column', fields.BoolField), ('integer_column', fields.IntegerField), ('float_column', fields.FloatField), ('decimal_column', fields.FloatField), ('percent_column', fields.PercentField), ('date_column', fields.DateField), ('datetime_column', fields.DatetimeField), ('unicode_column', fields.UnicodeField), ('null_column', fields.ByteField),]) expected_rows = [ {'float_column': 3.141592, 'decimal_column': 3.141592, 'bool_column': True, 'integer_column': 1, 'date_column': datetime.date(2015, 1, 1), 'datetime_column': datetime.datetime(2015, 8, 18, 15, 10), 'percent_column': Decimal('0.01'), 'unicode_column': 'Álvaro', 'null_column': ''.encode('utf-8')}, {'float_column': 1.234, 'decimal_column': 1.234, 'bool_column': False, 'integer_column': 2, 'date_column': datetime.date(1999, 2, 3), 'datetime_column': datetime.datetime(1999, 2, 3, 0, 1, 2), 'percent_column': Decimal('0.1169'), 'unicode_column': 'àáãâä¹²³', 'null_column': '-'.encode('utf-8')}, {'float_column': 4.56, 'decimal_column': 4.56, 'bool_column': True, 'integer_column': 3, 'date_column': datetime.date(2050, 1, 2), 'datetime_column': datetime.datetime(2050, 1, 2, 23, 45, 31), 'percent_column': Decimal('0.12'), 'unicode_column': 'éèẽêë', 'null_column': 'null'.encode('utf-8')}, {'float_column': 7.89, 'decimal_column': 7.89, 'bool_column': False, 'integer_column': 4, 'date_column': datetime.date(2015, 8, 18), 'datetime_column': datetime.datetime(2015, 8, 18, 22, 21, 33), 'percent_column': Decimal('0.1364'), 'unicode_column': '~~~~', 'null_column': 'nil'.encode('utf-8')}, {'float_column': 9.87, 'decimal_column': 9.87, 'bool_column': True, 'integer_column': 5, 'date_column': datetime.date(2015, 3, 4), 'datetime_column': datetime.datetime(2015, 3, 4, 16, 0, 1), 'percent_column': Decimal('0.1314'), 'unicode_column': 'álvaro', 'null_column': 'none'.encode('utf-8')}, {'float_column': 1.2345, 'decimal_column': 1.2345, 'bool_column': False, 'integer_column': 6, 'date_column': datetime.date(2015, 5, 6), 'datetime_column': datetime.datetime(2015, 5, 6, 12, 1, 2), 'percent_column': Decimal('0.02'), 'unicode_column': 'test', 'null_column': ''.encode('utf-8')},] table = Table(fields=expected_fields) for row in expected_rows: table.append(row) table._meta = {'test': 123} class RowsTestMixIn(object): maxDiff = None def setUp(self): self.files_to_delete = [] def tearDown(self): for filename in self.files_to_delete: os.unlink(filename) def assert_table_equal(self, first, second): self.assertDictEqual(dict(first.fields), dict(second.fields)) self.assertEqual(len(first), len(second)) for first_row, second_row in zip(first, second): self.assertDictEqual(dict(first_row._asdict()), dict(second_row._asdict())) def assert_file_contents_equal(self, first_filename, second_filename): with open(first_filename, 'rb') as fobj: first = fobj.read() with open(second_filename, 'rb') as fobj: second = fobj.read() self.assertEqual(first, second) rows-0.1.1/to-do/000077500000000000000000000000001257211624100135265ustar00rootroot00000000000000rows-0.1.1/to-do/ods_draft.py000066400000000000000000000037161257211624100160540ustar00rootroot00000000000000# coding: utf-8 import HTMLParser import zipfile from re import compile as regexp_compile, DOTALL from unicodedata import normalize html_parser = HTMLParser.HTMLParser() regexp_tags = regexp_compile(r'<[ \t]*[a-zA-Z0-9!"./_-]*[^>]*>', flags=DOTALL) regexp_comment = regexp_compile(r'', flags=DOTALL) regexp_ods_table = regexp_compile(r'(]*>)(.*?)' r'()', flags=DOTALL) regexp_ods_table_row = regexp_compile(r'(]*>)(.*?)' r'()', flags=DOTALL) regexp_ods_table_cell = regexp_compile(r'(]*>)(.*?)' r'()', flags=DOTALL) # TODO: encoding? # TODO: replace &...; # TODO: name/id of tables # TODO: re.MULTILINE # TODO: identify types # TODO: clear empty rows? # TODO: clear non-table rows? def tables_ods(filename, headers=False, strip_xml=True): zip_fobj = zipfile.ZipFile(filename) content = zip_fobj.open('content.xml').read() zip_fobj.close() return _tables_ods(content, headers, strip_xml) def _tables_ods(xml, headers, strip_xml): result = [] ods_tables = regexp_ods_table.split(xml)[2::4] for table_ods in ods_tables: table_data = [] rows = regexp_ods_table_row.split(table_ods)[2::4] if strip_xml: for row_data in rows: cells = regexp_ods_table_cell.split(row_data)[2::4] table_data.append([remove_html(field) for field in cells]) else: for row_data in rows: cells = regexp_ods_table_cell.split(row_data)[2::4] table_data.append([field.strip() for field in cells]) if headers: header, rows = table_data[0], table_data[1:] result.append([dict(zip(header, row)) for row in rows]) else: result.append(table_data) return result rows-0.1.1/to-do/plugin_mysql.py000066400000000000000000000137661257211624100166400ustar00rootroot00000000000000# coding: utf-8 # Copyright 2014 Álvaro Justen # 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, either version 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import datetime import MySQLdb from .rows import Table from .utils import ipartition, slug __all__ = [ 'import_from_mysql', 'export_to_mysql'] # TODO: replace 'None' with '' on export_to_* # TODO: need converters in and out # TODO: lazy=True|False # TODO: datetime.time on MYSQL_TYPE # TODO: import from mysql # TODO: logging? # TODO: _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone # # away') MYSQL_TYPE = {str: 'TEXT', int: 'INT', float: 'FLOAT', datetime.date: 'DATE', datetime.datetime: 'DATETIME', bool: 'BOOL'} # 'BOOL' on MySQL is a shortcut to TINYINT(1) MYSQLDB_TYPE = {getattr(MySQLdb.FIELD_TYPE, x): x \ for x in dir(MySQLdb.FIELD_TYPE) if not x.startswith('_')} MYSQLDB_TO_PYTHON = {'ENUM': str, 'STRING': str, 'VAR_STRING': str, 'BLOB': bytes, 'LONG_BLOB': bytes, 'MEDIUM_BLOB': bytes, 'TINY_BLOB': bytes, 'DECIMAL': float, 'DOUBLE': float, 'FLOAT': float, 'INT24': int, 'LONG': int, 'LONGLONG': int, 'TINY': int, 'YEAR': int, 'DATE': datetime.date, 'NEWDATE': datetime.date, 'TIME': int, 'TIMESTAMP': int, 'DATETIME': datetime.datetime} def _get_mysql_config(connection_str): colon_index = connection_str.index(':') at_index = connection_str.index('@') slash_index = connection_str.index('/') config = {} config['user'] = connection_str[:colon_index] config['passwd'] = connection_str[colon_index + 1:at_index] config['host'] = connection_str[at_index + 1:slash_index] config['port'] = 3306 if ':' in config['host']: data = config['host'].split(':') config['host'] = data[0] config['port'] = int(data[1]) if connection_str.count('/') == 1: table_name = None config['db'] = connection_str[slash_index + 1:] else: second_slash_index = connection_str.index('/', slash_index + 1) config['db'] = connection_str[slash_index + 1:second_slash_index] table_name = connection_str[second_slash_index + 1:] return config, table_name def _connect_to_mysql(config): return MySQLdb.connect(**config) def import_from_mysql(connection_string, limit=None, order_by=None, query=''): #TODO: add 'lazy' option config, table_name = _get_mysql_config(connection_string) connection = _connect_to_mysql(config) cursor = connection.cursor() if query: sql = query else: sql = 'SELECT * FROM ' + table_name if limit is not None: sql += ' LIMIT {0[0]}, {0[1]}'.format(limit) if order_by is not None: sql += ' ORDER BY ' + order_by cursor.execute(sql) column_info = [(x[0], x[1]) for x in cursor.description] table = Table(fields=[x[0] for x in cursor.description]) table.types = {name: MYSQLDB_TO_PYTHON[MYSQLDB_TYPE[type_]] \ for name, type_ in column_info} table_rows = [list(row) for row in cursor.fetchall()] encoding = connection.character_set_name() for row in table_rows: for column_index, value in enumerate(row): if type(value) is str: row[column_index] = value.decode(encoding) table._rows = table_rows cursor.close() connection.close() return table def export_to_mysql(table, connection_string, encoding=None, batch_size=1000, commit_every=10000, callback=None, callback_every=10000): config, table_name = _get_mysql_config(connection_string) connection = _connect_to_mysql(config) cursor = connection.cursor() # Create table fields, types = table.fields, table.types field_slugs = [slug(field) for field in fields] field_types = [MYSQL_TYPE[types[field]] for field in fields] columns_definition = ['{} {}'.format(field, type_) for field, type_ in zip(field_slugs, field_types)] sql = 'CREATE TABLE IF NOT EXISTS {} ({})'\ .format(table_name, ', '.join(columns_definition)) cursor.execute(sql) # Insert items columns = ', '.join(field_slugs) #placeholders = ['%s' if types[field] in (int, float, bool) else '"%s"' # for field in fields] # TODO: fix this string/formatting problem placeholders = ['%s' for field in fields] sql = 'INSERT INTO {} ({}) VALUES ({})'.format(table_name, columns, ', '.join(placeholders)) total = last_commit = last_callback = 0 for rows in ipartition(iter(table), batch_size): values = [[row[field] for field in fields] for row in rows] added = len(values) total += added last_commit += added last_callback += added cursor.executemany(sql, values) if last_commit >= commit_every: connection.commit() last_commit = 0 if callback is not None and last_callback >= callback_every: callback(total) last_callback = 0 if callback is not None and last_callback > 0: callback(total) if last_commit > 0: connection.commit() connection.close()