├── .coveragerc ├── .gitignore ├── .travis.yml ├── COPYING ├── CepTracker.py ├── Dockerfile ├── IbgeTracker.py ├── Makefile ├── PackTracker.py ├── PostmonServer.py ├── PostmonTaskScheduler.py ├── README.md ├── database.py ├── docs └── openapi.json ├── log.yaml ├── requirements-dev.txt ├── requirements.txt ├── run.wsgi ├── test ├── assets │ └── buscacepinter │ │ ├── 01330000.json │ │ ├── 12245230.json │ │ ├── 65930000.json │ │ ├── 69908768.json │ │ ├── 75064590.json │ │ └── 99999999.json ├── database_test.py └── postmon_test.py ├── utils.py └── views └── crossdomain.tpl /.coveragerc: -------------------------------------------------------------------------------- 1 | [report] 2 | omit = 3 | */python?.?/* 4 | */site-packages/nose/* 5 | */packtrack/* 6 | */bottle.py 7 | */bottle/* 8 | */test/* -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.*~ 3 | *.swp 4 | run.py 5 | build 6 | celerybeat-schedule 7 | *.log 8 | .coverage -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - "2.7" 5 | 6 | before_install: 7 | - pip install -r requirements-dev.txt coveralls 8 | 9 | script: make coverage 10 | 11 | services: mongodb 12 | 13 | after_success: 14 | - coveralls 15 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /CepTracker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from datetime import datetime 4 | import logging 5 | import os 6 | import re 7 | 8 | import requests 9 | 10 | logger = logging.getLogger(__name__) 11 | _notfound_key = '__notfound__' 12 | 13 | 14 | class CepTracker(object): 15 | url = os.getenv( 16 | "CORREIOS_CEP_URL", 17 | "https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php", # NOQA 18 | ) 19 | 20 | def _request(self, cep): 21 | response = requests.post(self.url, data={ 22 | "pagina": "/app/endereco/index.php", 23 | "cepaux": "", 24 | "mensagem_alerta": "", 25 | "endereco": cep, 26 | "tipoCEP": "ALL", 27 | }, headers={ 28 | "Referer": "https://buscacepinter.correios.com.br/app/endereco/index.php?t", 29 | }, timeout=10) 30 | try: 31 | response.raise_for_status() 32 | except requests.exceptions.HTTPError as ex: 33 | logger.exception('Erro no site dos Correios') 34 | raise ex 35 | return response.json() 36 | 37 | def track(self, cep): 38 | data = self._request(cep) 39 | result = [] 40 | 41 | found = False 42 | now = datetime.now() 43 | 44 | for item in data["dados"]: 45 | if item['cep'] == cep: 46 | found = True 47 | 48 | data = { 49 | "_meta": { 50 | "v_date": now, 51 | }, 52 | "cep": item['cep'], 53 | "bairro": item['bairro'], 54 | "cidade": item['localidade'], 55 | "estado": item['uf'], 56 | } 57 | logradouro = item["logradouroDNEC"] 58 | if ' - ' in logradouro: 59 | logradouro, complemento = logradouro.split(' - ', 1) 60 | data['complemento'] = complemento.strip(' -') 61 | data['logradouro'] = logradouro 62 | 63 | result.append(data) 64 | 65 | if not found: 66 | result.append({ 67 | 'cep': cep, 68 | '_meta': { 69 | "v_date": now, 70 | _notfound_key: True, 71 | }, 72 | }) 73 | return result 74 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:xenial 2 | MAINTAINER Bluesoft Fire 3 | 4 | ENV DEBIAN_FRONTEND noninteractive 5 | 6 | RUN apt-get -y update -qq&& \ 7 | apt-get -y install \ 8 | gcc \ 9 | ipython \ 10 | libz-dev \ 11 | libxml2-dev \ 12 | libxslt1-dev \ 13 | mongodb \ 14 | python2.7 \ 15 | python2.7-dev \ 16 | libyaml-dev \ 17 | libpython2.7-dev \ 18 | python-pip 19 | 20 | RUN pip install --upgrade pip==18.0 21 | 22 | RUN pip install setuptools wheel 23 | 24 | ENV APP_DIR /srv/postmon 25 | 26 | RUN mkdir -p $APP_DIR 27 | ADD . $APP_DIR 28 | WORKDIR $APP_DIR 29 | 30 | RUN pip install -r requirements.txt 31 | RUN mkdir -p data/db 32 | 33 | EXPOSE 9876 34 | 35 | ENTRYPOINT mongod \ 36 | --fork \ 37 | --logpath /tmp/mongo.log \ 38 | --dbpath data/db && \ 39 | python PostmonServer.py 40 | 41 | -------------------------------------------------------------------------------- /IbgeTracker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import requests 4 | 5 | from database import MongoDb as Database 6 | from utils import slug 7 | 8 | 9 | class IbgeTracker(): 10 | 11 | def __init__(self): 12 | base_url = 'https://raw.githubusercontent.com/PostmonAPI/ibge-parser/master/data/postmon' # noqa 13 | self.url_ufs = base_url + '/ufs.json' 14 | self.url_cidades = base_url + '/cidades.json' 15 | 16 | def _request(self, url): 17 | response = requests.get(url) 18 | response.raise_for_status() 19 | return response.json() 20 | 21 | def _get_info_ufs(self, siglas): 22 | return self._request(self.url_ufs) 23 | 24 | def _get_info_cidades(self): 25 | return self._request(self.url_cidades) 26 | 27 | def _track_ufs(self, db, siglas): 28 | infos = self._get_info_ufs(siglas) 29 | for info in infos: 30 | db.insert_or_update_uf(info) 31 | 32 | def _track_cidades(self, db): 33 | infos = self._get_info_cidades() 34 | siglas = {} 35 | for info in infos: 36 | codigo_ibge_uf = info['codigo_ibge_uf'] 37 | sigla_uf = info['sigla_uf'] 38 | nome = info['nome'] 39 | if codigo_ibge_uf not in siglas: 40 | siglas[codigo_ibge_uf] = sigla_uf 41 | 42 | # a chave única de uma cidade não 43 | # pode ser só o nome, pois 44 | # existem cidades com mesmo nome 45 | # em estados diferentes 46 | info['sigla_uf_nome_cidade'] = slug('%s_%s' % (sigla_uf, nome)) 47 | 48 | db.insert_or_update_cidade(info) 49 | 50 | return siglas 51 | 52 | def track(self, db): 53 | """ 54 | Atualiza as bases internas do mongo 55 | com os dados mais recentes do IBGE 56 | referente a ufs e cidades 57 | """ 58 | siglas = self._track_cidades(db) 59 | # siglas é um dict cod_ibge -> sigla: 60 | # { '35': 'SP', '35': 'RJ', ... } 61 | self._track_ufs(db, siglas) 62 | 63 | 64 | def _standalone(): 65 | db = Database() 66 | ibge = IbgeTracker() 67 | ibge.track(db) 68 | 69 | 70 | if __name__ == "__main__": 71 | _standalone() 72 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | .PHONY: test 3 | test: pep8 4 | nosetests 5 | 6 | .PHONY: coverage 7 | coverage: pep8 8 | nosetests --with-cover 9 | 10 | .PHONY: pep8 11 | pep8: 12 | @flake8 * --ignore=F403,F401 --exclude=*.txt,*.pyc,*.md,COPYING,Makefile,*.wsgi,*celerybeat-schedule*,*.yaml,*.log,Dockerfile 13 | -------------------------------------------------------------------------------- /PackTracker.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import json 3 | import os 4 | 5 | import packtrack 6 | import requests 7 | 8 | from database import MongoDb as Database 9 | 10 | 11 | def correios(track, backend=None, auth=None): 12 | if backend is None: 13 | backend = os.getenv('ECT_BACKEND') 14 | encomenda = packtrack.Correios.track(track, backend=backend, auth=auth) 15 | 16 | if not encomenda: 17 | raise ValueError(u"Encomenda nao encontrada.") 18 | if not encomenda.status: 19 | raise ValueError(u"A encomenda ainda nao tem historico.") 20 | 21 | result = [] 22 | for status in encomenda.status: 23 | historico = { 24 | 'data': status.data, 25 | 'local': status.local, 26 | 'situacao': status.situacao, 27 | 'detalhes': status.detalhes, 28 | } 29 | result.append(historico) 30 | return result 31 | 32 | 33 | def register(provider, track, callback): 34 | """ 35 | Registra o pacote para acompanhamento. 36 | """ 37 | db = Database() 38 | return db.packtrack.register(provider, track, callback) 39 | 40 | 41 | def run(provider, track): 42 | db = Database() 43 | obj = db.packtrack.get_one(provider, track) 44 | 45 | if provider != 'ect': 46 | raise ValueError(u"Unexpected provider: %s" % provider) 47 | 48 | try: 49 | data = correios(track) 50 | except ValueError: 51 | return False 52 | 53 | changed = obj.get('historico') != data 54 | db.packtrack.update(provider, track, data, changed=changed) 55 | return changed 56 | 57 | 58 | def report(provider, track): 59 | db = Database() 60 | obj = db.packtrack.get_one(provider, track) 61 | 62 | _meta = obj.pop('_meta') 63 | callbacks = _meta.pop('callbacks') 64 | 65 | for callback in callbacks: 66 | data = obj.copy() 67 | url = callback['callback'] 68 | data['input'] = callback 69 | headers = {'Content-Type': 'application/json'} 70 | requests.post( 71 | url, 72 | headers=headers, 73 | data=json.dumps(data)) 74 | -------------------------------------------------------------------------------- /PostmonServer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from datetime import datetime, timedelta 4 | import os 5 | import bottle 6 | import json 7 | import logging 8 | import xmltodict 9 | from bottle import run, request, response, template, HTTPResponse 10 | from bottle.ext.healthcheck import HealthCheck 11 | from raven import Client 12 | from raven.contrib.bottle import Sentry 13 | 14 | from CepTracker import CepTracker, _notfound_key 15 | import PackTracker 16 | import requests 17 | from database import MongoDb as Database 18 | from utils import EnableCORS 19 | 20 | logger = logging.getLogger(__name__) 21 | HealthCheck(bottle, "/__health__") 22 | 23 | app = bottle.default_app() 24 | app.catchall = False 25 | app_v1 = bottle.Bottle() 26 | app_v1.catchall = False 27 | jsonp_query_key = 'callback' 28 | 29 | db = Database() 30 | db.create_indexes() 31 | 32 | 33 | def validate_format(callback): 34 | def wrapper(*args, **kwargs): 35 | output_format = request.query.format 36 | if output_format and output_format not in {'json', 'jsonp', 'xml'}: 37 | message = "400 Parametro format='%s' invalido." % output_format 38 | return make_error(message, output_format='json') 39 | return callback(*args, **kwargs) 40 | return wrapper 41 | 42 | 43 | def _notfound(record): 44 | _meta = record.get('_meta', {}) 45 | return _notfound_key in _meta or _notfound_key in record 46 | 47 | 48 | def expired(record_date): 49 | _meta = record_date.get('_meta', {}) 50 | v_date = _meta.get('v_date') or record_date.get('v_date') 51 | if not v_date: 52 | return True 53 | 54 | if _notfound(record_date): 55 | # 1 week 56 | WEEKS = 1 57 | else: 58 | # 6 months 59 | WEEKS = 26 60 | 61 | now = datetime.now() 62 | return (now - v_date >= timedelta(weeks=WEEKS)) 63 | 64 | 65 | def _get_info_from_source(cep): 66 | tracker = CepTracker() 67 | return tracker.track(cep) 68 | 69 | 70 | def format_result(result): 71 | # checa se foi solicitada resposta em JSONP 72 | js_func_name = bottle.request.query.get(jsonp_query_key) 73 | 74 | # checa se foi solicitado xml 75 | format = bottle.request.query.get('format') 76 | if format == 'xml': 77 | response.content_type = 'application/xml' 78 | return xmltodict.unparse({'result': result}) 79 | 80 | if js_func_name: 81 | # se a resposta vai ser JSONP, o content type deve ser js e seu 82 | # conteudo deve ser JSON 83 | response.content_type = 'application/javascript' 84 | result = json.dumps(result) 85 | 86 | result = '%s(%s);' % (js_func_name, result) 87 | return result 88 | 89 | 90 | def make_error(message, output_format=None): 91 | formats = { 92 | 'json': 'application/json', 93 | 'xml': 'application/xml', 94 | 'jsonp': 'application/javascript', 95 | } 96 | format_ = output_format or bottle.request.query.get('format', 'json') 97 | response = HTTPResponse(status=message, content_type=formats[format_]) 98 | response.headers['Access-Control-Allow-Origin'] = '*' 99 | return response 100 | 101 | 102 | def _get_estado_info(db, sigla): 103 | sigla = sigla.upper() 104 | return db.get_one_uf(sigla, fields={'_id': False, 'sigla': False}) 105 | 106 | 107 | def _get_cidade_info(db, sigla_uf, nome_cidade): 108 | fields = { 109 | '_id': False, 110 | 'sigla_uf': False, 111 | 'codigo_ibge_uf': False, 112 | 'sigla_uf_nome_cidade': False, 113 | 'nome': False 114 | } 115 | return db.get_one_cidade(sigla_uf, nome_cidade, fields=fields) 116 | 117 | 118 | @app.route('/cep/') 119 | @app_v1.route('/cep/') 120 | def verifica_cep(cep): 121 | cep = cep.replace('-', '') 122 | db = Database() 123 | response.headers['Access-Control-Allow-Origin'] = '*' 124 | message = None 125 | result = db.get_one(cep, fields={'_id': False}) 126 | if not result or expired(result): 127 | result = None 128 | try: 129 | info = _get_info_from_source(cep) 130 | except requests.exceptions.RequestException: 131 | message = '503 Servico Temporariamente Indisponivel' 132 | logger.exception(message) 133 | return make_error(message) 134 | else: 135 | for item in info: 136 | db.insert_or_update(item) 137 | result = db.get_one(cep, fields={ 138 | '_id': False, 'v_date': False}) 139 | 140 | if result: 141 | notfound = _notfound(result) 142 | else: 143 | notfound = True 144 | 145 | if notfound: 146 | message = '404 CEP %s nao encontrado' % cep 147 | return make_error(message) 148 | 149 | result.pop('v_date', None) 150 | result.pop('_meta', None) 151 | 152 | response.headers['Cache-Control'] = 'public, max-age=2592000' 153 | sigla_uf = result['estado'] 154 | estado_info = _get_estado_info(db, sigla_uf) 155 | if estado_info: 156 | result['estado_info'] = estado_info 157 | nome_cidade = result['cidade'] 158 | cidade_info = _get_cidade_info(db, sigla_uf, nome_cidade) 159 | if cidade_info: 160 | result['cidade_info'] = cidade_info 161 | return format_result(result) 162 | 163 | 164 | @app_v1.route('/uf/') 165 | def uf(sigla): 166 | response.headers['Access-Control-Allow-Origin'] = '*' 167 | db = Database() 168 | result = _get_estado_info(db, sigla) 169 | if result: 170 | response.headers['Cache-Control'] = 'public, max-age=2592000' 171 | return format_result(result) 172 | else: 173 | message = '404 Estado %s nao encontrado' % sigla 174 | logger.warning(message) 175 | return make_error(message) 176 | 177 | 178 | @app_v1.route('/cidade//') 179 | def cidade(sigla_uf, nome): 180 | response.headers['Access-Control-Allow-Origin'] = '*' 181 | db = Database() 182 | result = _get_cidade_info(db, sigla_uf, nome.decode('utf-8')) 183 | if result: 184 | response.headers['Cache-Control'] = 'public, max-age=2592000' 185 | return format_result(result) 186 | else: 187 | message = '404 Cidade %s-%s nao encontrada' % (nome, sigla_uf) 188 | logger.warning(message) 189 | return make_error(message) 190 | 191 | 192 | @app_v1.route('/rastreio//') 193 | def track_pack(provider, track): 194 | response.headers['Access-Control-Allow-Origin'] = '*' 195 | if provider == 'ect': 196 | auth = ( 197 | request.headers.get('x-correios-usuario'), 198 | request.headers.get('x-correios-senha'), 199 | ) 200 | if auth == (None, None): 201 | auth = None 202 | 203 | try: 204 | historico = PackTracker.correios(track, auth=auth) 205 | except (AttributeError, ValueError): 206 | message = "404 Pacote %s nao encontrado" % track 207 | logger.exception(message) 208 | else: 209 | return format_result({ 210 | 'servico': provider, 211 | 'codigo': track, 212 | 'historico': historico, 213 | }) 214 | else: 215 | message = '404 Servico %s nao encontrado' % provider 216 | logger.warning(message) 217 | return make_error(message) 218 | 219 | 220 | @app_v1.route('/rastreio/') 221 | def track_pack_token(token): 222 | return make_error('404 NOT IMPLEMENTED') 223 | 224 | 225 | @app_v1.route('/rastreio//', method='POST') 226 | def track_pack_register(provider, track): 227 | """ 228 | Registra o rastreamento do pacote. O `callback` é parâmetro obrigatório, 229 | qualquer outra informação passada será devolvida quando o `callback` for 230 | chamado. 231 | 232 | { 233 | "callback": "http://httpbin.org/post", 234 | "myid": 1, 235 | "other": "thing" 236 | } 237 | """ 238 | if "callback" not in request.json: 239 | message = "400 callback obrigatorio" 240 | return make_error(message) 241 | 242 | try: 243 | result = PackTracker.register(provider, track, request.json) 244 | except (AttributeError, ValueError): 245 | message = "400 Falha no registro do %s/%s" % (provider, track) 246 | logger.exception(message) 247 | return make_error(message) 248 | else: 249 | return format_result({ 250 | 'token': result, 251 | }) 252 | 253 | 254 | @app.route('/crossdomain.xml') 255 | def crossdomain(): 256 | response.content_type = 'application/xml' 257 | return template('crossdomain') 258 | 259 | 260 | app.install(validate_format) 261 | app_v1.install(validate_format) 262 | app.install(EnableCORS()) 263 | app_v1.install(EnableCORS()) 264 | app.mount('/v1', app_v1) 265 | 266 | SENTRY_DSN = os.getenv('SENTRY_DSN') 267 | if SENTRY_DSN: 268 | sentry_client = Client(SENTRY_DSN) 269 | app = Sentry(app, sentry_client) 270 | app_v1 = Sentry(app_v1, sentry_client) 271 | 272 | 273 | def _standalone(port=9876): 274 | run(app=app, host='0.0.0.0', port=port) 275 | 276 | 277 | if __name__ == "__main__": 278 | _standalone() 279 | -------------------------------------------------------------------------------- /PostmonTaskScheduler.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from datetime import timedelta 4 | from celery import Celery 5 | from celery.utils.log import get_task_logger 6 | from IbgeTracker import IbgeTracker 7 | import PackTracker 8 | from database import MongoDb as Database 9 | import os 10 | 11 | USERNAME = os.environ.get('POSTMON_DB_USER') 12 | PASSWORD = os.environ.get('POSTMON_DB_PASSWORD') 13 | HOST = os.environ.get('POSTMON_DB_HOST', 'localhost') 14 | PORT = os.environ.get('POSTMON_DB_PORT', '27017') 15 | 16 | if all((USERNAME, PASSWORD)): 17 | broker_conn_string = 'mongodb://%s:%s@%s:%s' \ 18 | % (USERNAME, PASSWORD, HOST, PORT) 19 | else: 20 | broker_conn_string = 'mongodb://%s:%s' % (HOST, PORT) 21 | 22 | print(broker_conn_string) 23 | 24 | app = Celery('postmon', broker=broker_conn_string) 25 | 26 | app.conf.update( 27 | CELERY_TASK_SERIALIZER='json', 28 | CELERY_ACCEPT_CONTENT=['json'], # Ignore other content 29 | CELERY_RESULT_SERIALIZER='json', 30 | CELERY_TIMEZONE='America/Sao_Paulo', 31 | CELERY_ENABLE_UTC=True, 32 | CELERYBEAT_SCHEDULE={ 33 | 'track_ibge_daily': { 34 | 'task': 'PostmonTaskScheduler.track_ibge', 35 | 'schedule': timedelta(days=1) # útil para 36 | # testes: timedelta(minutes=1) 37 | }, 38 | 'track_packs': { 39 | 'task': 'PostmonTaskScheduler.track_packs', 40 | 'schedule': timedelta(hours=1), 41 | } 42 | 43 | } 44 | ) 45 | 46 | logger = get_task_logger(__name__) 47 | 48 | 49 | @app.task 50 | def track_ibge(): 51 | logger.info('Iniciando tracking do IBGE...') 52 | db = Database() 53 | ibge = IbgeTracker() 54 | ibge.track(db) 55 | logger.info('Finalizou o tracking do IBGE') 56 | 57 | 58 | @app.task 59 | def track_packs(): 60 | logger.info('Iniciando tracking de pacotes...') 61 | db = Database() 62 | for obj in db.packtrack.get_all(): 63 | provider = obj['servico'] 64 | track = obj['codigo'] 65 | changed = PackTracker.run(provider, track) 66 | if changed: 67 | PackTracker.report(provider, track) 68 | 69 | logger.info('Finalizou o tracking de pacotes') 70 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Postmon [](http://travis-ci.org/PostmonAPI/postmon) [![Coverage Status](https://coveralls.io/repos/github/PostmonAPI/postmon/badge.svg?branch=master)](https://coveralls.io/github/PostmonAPI/postmon?branch=master) 2 | 3 | ========== 4 | API para consulta de CEP's e relacionados 5 | 6 | Requisitos do ambiente de desenvolvimento 7 | --------------------------------------------- 8 | * MongoDB 9 | * Python 2.7 10 | * iPython (recomendado) 11 | 12 | Requisitos do ambiente Python 13 | ----------------------- 14 | 15 | As dependências estão listadas no arquivo requirements.txt. 16 | 17 | * requests 18 | * pymongo 19 | * bottle 20 | * nosetests 21 | * webtest 22 | * packtrack 23 | * celery 24 | 25 | Rodando testes 26 | ---------------- 27 | Executar o comando: 28 | 29 | make test 30 | 31 | na raiz do projeto. 32 | 33 | Rodando a aplicação localmente na porta 9876 34 | -------------------------------- 35 | 36 | $ python PostmonServer.py 37 | 38 | ou 39 | 40 | $ ipython -i PostmonServer.py 41 | >> _standalone() 42 | 43 | Caso queira rodar em outra porta, basta passá-la como parametro no chamado do _standalone 44 | 45 | Para rodar o [Scheduler](#scheduler): 46 | 47 | $ celery worker -B -A PostmonTaskScheduler -l info 48 | 49 | Recomenda-se a utilização do [Supervisord](http://supervisord.org/) para manter o Celery rodando. Exemplo de configuração para o _supervisord.conf_: 50 | 51 | [program:celeryd] 52 | command=celery worker -B -A PostmonTaskScheduler -l info 53 | directory=POSTMON_HOME/repositorio 54 | stdout_logfile=POSTMON_LOG_DIR/celeryd.log 55 | stderr_logfile=POSTMON_LOG_DIR/celeryd_err.log 56 | autostart=true 57 | autorestart=true 58 | startsecs=10 59 | stopwaitsecs=600 60 | 61 | Executando a aplicação no Docker 62 | ------------------------ 63 | 64 | Se você tem o Docker instalado, pode fazer o build da imagem e rodar o Postmon em um container. 65 | 66 | ```bash 67 | $ docker build -t postmon . 68 | $ docker run -d -p 80:9876 postmon 69 | ``` 70 | 71 | Acesse o endereço `http:///v1/cep/`, por exemplo `http://127.0.0.1/v1/cep/01311940`. 72 | 73 | 74 | MongoDB com autenticação 75 | ------------------------ 76 | 77 | Se o seu MongoDB possui autenticação habilitada você deverá configurar o banco do postmon 78 | e também exportar duas variavéis de ambiente. 79 | 80 | ```javascript 81 | mongo 82 | > use postmon 83 | > db.addUser('admin', '123456') 84 | ``` 85 | 86 | Agora que seu Mongo está com password exporte as variaveis de ambiente. 87 | 88 | ```bash 89 | export POSTMON_DB_USER=admin 90 | export POSTMON_DB_PASSWORD=123456 91 | ``` 92 | 93 | Para conectar em um banco remoto exporte a variável de ambiente: 94 | ```bash 95 | export POSTMON_DB_HOST= 96 | ``` 97 | 98 | Scheduler 99 | --------- 100 | 101 | O Postmon conta com um scheduler baseado na ferramenta [Celery](http://www.celeryproject.org/). Até o momento, a única funcionalidade implementada nessa estrutura é a rotina de coleta de dados do [IBGE](#ibge). 102 | 103 | O Celery usa, como Broker, a mesma instância do MongoDB utilizada no módulo de CEP. 104 | 105 | O comando apresentado na seção [rodando a aplicação](#rodando-a-aplicação-localmente-na-porta-9876) pode ser quebrado em dois caso seja necessário rodar o Celery Worker separado do Celery Beat. Para mais informações sobre essa questão leia a [documentação do Celery](http://docs.celeryproject.org/en/latest/). 106 | 107 | Além do Broker, o Celery Beat depende internamente de uma base de dados, criada automaticamente na primeira execução, onde são armazenadas informações sobre os schedules. Por padrão essa base fica em um arquivo chamado _celerybeat_schedule_, criado no diretório onde o Celery Beat foi executado. Esse local pode ser alterado através do switch -s, conforme exemplo abaixo: 108 | 109 | $ celery worker -B -A PostmonTaskScheduler -l info -s /novo/caminho/para/arquivo/celerybeat_schedule 110 | 111 | IBGE 112 | ------------- 113 | 114 | O Postmon fornece as seguintes informações extraídas do site do IBGE: 115 | 116 | * Código do município/UF 117 | * Área territorial (em km²) 118 | 119 | Essas informações estão presentes nos atributos *estado_info* e *cidade_info* da rota de busca de _cep_, bem como nas seguintes rotas: 120 | 121 | * /uf/{sigla-uf} 122 | * /cidade/{sigla-uf}/{nome-cidade} 123 | 124 | Exemplos: 125 | 126 | * /uf/SP 127 | * /cidade/SP/São Paulo 128 | * /cidade/SP/Araraquara 129 | * /cidade/RJ/Macaé 130 | 131 | A rotina de atualização desses dados está configurada para rodar diariamente. 132 | 133 | Postmon - The Mongo Postman API 134 | Copyright (C) 2013 Coding For Change 135 | 136 | This program is free software: you can redistribute it and/or modify 137 | it under the terms of the GNU General Public License as published by 138 | the Free Software Foundation, either version 3 of the License, or 139 | (at your option) any later version. 140 | 141 | This program is distributed in the hope that it will be useful, 142 | but WITHOUT ANY WARRANTY; without even the implied warranty of 143 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 144 | GNU General Public License for more details. 145 | 146 | You should have received a copy of the GNU General Public License 147 | along with this program. If not, see . 148 | -------------------------------------------------------------------------------- /database.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from datetime import datetime 4 | import os 5 | import re 6 | 7 | import pymongo 8 | 9 | from utils import slug 10 | 11 | 12 | class MongoDb(object): 13 | 14 | _fields = [ 15 | 'logradouro', 16 | 'bairro', 17 | 'cidade', 18 | 'estado', 19 | 'complemento' 20 | ] 21 | 22 | def __init__(self): 23 | DATABASE = os.environ.get('POSTMON_DB_NAME', 'postmon') 24 | HOST = os.environ.get('POSTMON_DB_HOST', 'localhost') 25 | PORT = int(os.environ.get('POSTMON_DB_PORT', 27017)) 26 | USERNAME = os.environ.get('POSTMON_DB_USER') 27 | PASSWORD = os.environ.get('POSTMON_DB_PASSWORD') 28 | 29 | self._client = pymongo.MongoClient(HOST, PORT) 30 | self._db = self._client[DATABASE] 31 | if all((USERNAME, PASSWORD)): 32 | self._db.authenticate(USERNAME, PASSWORD) 33 | self.packtrack = PackTrack(self._db.packtrack) 34 | 35 | def create_indexes(self): 36 | self._db.ceps.ensure_index('cep') 37 | 38 | def get_one(self, cep, **kwargs): 39 | r = self._db.ceps.find_one({'cep': cep}, **kwargs) 40 | if r and u'endereço' in r and 'endereco' not in r: 41 | # Garante que o cache também tem a key `endereco`. #92 42 | # Novos resultados já são adicionados corretamente. 43 | r['endereco'] = r[u'endereço'] 44 | return r 45 | 46 | def get_one_uf(self, sigla, **kwargs): 47 | return self._db.ufs.find_one({'sigla': sigla}, **kwargs) 48 | 49 | def get_one_cidade(self, sigla_uf, nome_cidade, **kwargs): 50 | def key_func(_uf, _cidade): 51 | return u'{}_{}'.format(slug(_uf), slug(_cidade)) 52 | sigla_uf_nome_cidade = key_func(sigla_uf, nome_cidade) 53 | spec = {'sigla_uf_nome_cidade': sigla_uf_nome_cidade} 54 | 55 | search = re.search(r'\((.+)\)', nome_cidade) 56 | if search: 57 | nome_cidade_alternativa = search.group(1) 58 | spec_alternativa = { 59 | 'sigla_uf_nome_cidade': key_func( 60 | sigla_uf, nome_cidade_alternativa) 61 | } 62 | spec = {'$or': [spec, spec_alternativa]} 63 | return self._db.cidades.find_one(spec, **kwargs) 64 | 65 | def get_one_uf_by_nome(self, nome, **kwargs): 66 | return self._db.ufs.find_one({'nome': nome}, **kwargs) 67 | 68 | def insert_or_update(self, obj, **kwargs): 69 | 70 | update = {'$set': obj} 71 | empty_fields = set(self._fields) - set(obj) 72 | if empty_fields: 73 | update['$unset'] = dict((x, 1) for x in empty_fields) 74 | 75 | self._db.ceps.update({'cep': obj['cep']}, update, upsert=True) 76 | 77 | def insert_or_update_uf(self, obj, **kwargs): 78 | update = {'$set': obj} 79 | self._db.ufs.update({'sigla': obj['sigla']}, update, upsert=True) 80 | 81 | def insert_or_update_cidade(self, obj, **kwargs): 82 | update = {'$set': obj} 83 | chave = 'sigla_uf_nome_cidade' 84 | self._db.cidades.update({chave: obj[chave]}, update, upsert=True) 85 | 86 | def remove(self, cep): 87 | self._db.ceps.remove({'cep': cep}) 88 | 89 | 90 | class PackTrack(object): 91 | 92 | def __init__(self, collection): 93 | self._collection = collection 94 | 95 | def _patch(self, obj): 96 | try: 97 | _id = obj.pop('_id') 98 | except KeyError: 99 | return 100 | else: 101 | obj['token'] = str(_id) 102 | 103 | def get_one(self, provider, track): 104 | spec = {'servico': provider, 'codigo': track} 105 | obj = self._collection.find_one(spec) 106 | self._patch(obj) 107 | return obj 108 | 109 | def get_all(self): 110 | objs = list(self._collection.find()) 111 | for obj in objs: 112 | self._patch(obj) 113 | return objs 114 | 115 | def register(self, provider, track, callback): 116 | key = {'servico': provider, 'codigo': track} 117 | data = { 118 | '$addToSet': { 119 | '_meta.callbacks': callback, 120 | }, 121 | '$setOnInsert': { 122 | '_meta.created_at': datetime.utcnow(), 123 | '_meta.changed_at': None, 124 | '_meta.checked_at': None, 125 | }, 126 | } 127 | self._collection.find_and_modify(key, data, upsert=True) 128 | obj = self._collection.find_one(key) 129 | self._patch(obj) 130 | return obj['token'] 131 | 132 | def update(self, provider, track, data, changed): 133 | key = {'servico': provider, 'codigo': track} 134 | now = datetime.utcnow() 135 | 136 | set_ = { 137 | "_meta.checked_at": now 138 | } 139 | if changed: 140 | set_.update({ 141 | '_meta.changed_at': now, 142 | 'historico': data, 143 | }) 144 | 145 | query = {"$set": set_} 146 | self._collection.update(key, query) 147 | -------------------------------------------------------------------------------- /docs/openapi.json: -------------------------------------------------------------------------------- 1 | { 2 | "openapi" : "3.0.2", 3 | "info" : { 4 | "title" : "Postmon", 5 | "description" : "Uma API para consultar CEP", 6 | "version" : "1.0.0" 7 | }, 8 | "servers" : [ { 9 | "url" : "https://api.postmon.com.br/v1/" 10 | } ], 11 | "paths" : { 12 | "/cep" : { 13 | "get" : { 14 | "summary" : "Retorna os dados do endereço para o CEP passado", 15 | "description" : "Retorna os dados do endereço para o CEP passado. CEP deve ser enviado no formato de 8 dígitos.", 16 | "operationId" : "getCEPData", 17 | "parameters" : [ { 18 | "name" : "cep", 19 | "in" : "path", 20 | "description" : "Valor do CEP com apenas os 8 digitos.", 21 | "required" : true, 22 | "style" : "simple", 23 | "explode" : false, 24 | "schema" : { 25 | "type" : "string" 26 | } 27 | } ], 28 | "responses" : { 29 | "200" : { 30 | "description" : "encontrado", 31 | "content" : { 32 | "application/json" : { 33 | "schema" : { 34 | "$ref" : "#/components/schemas/CEPResponse" 35 | } 36 | } 37 | } 38 | } 39 | } 40 | } 41 | } 42 | }, 43 | "components" : { 44 | "schemas" : { 45 | "CEPResponse" : { 46 | "required" : [ "estado", "logradouro" ], 47 | "type" : "object", 48 | "properties" : { 49 | "estado" : { 50 | "type" : "string", 51 | "example" : "RJ" 52 | }, 53 | "logradouro" : { 54 | "type" : "string", 55 | "example" : "Rua do Bispo" 56 | }, 57 | "cidade" : { 58 | "type" : "string", 59 | "example" : "Rio de Janeiro" 60 | }, 61 | "bairro" : { 62 | "type" : "string", 63 | "example" : "Tijuca" 64 | }, 65 | "estadoInfo" : { 66 | "$ref" : "#/components/schemas/EstadoInfo" 67 | }, 68 | "cidadeInfo" : { 69 | "$ref" : "#/components/schemas/CidadeInfo" 70 | } 71 | } 72 | }, 73 | "EstadoInfo" : { 74 | "type" : "object", 75 | "properties" : { 76 | "area_km2" : { 77 | "type" : "string", 78 | "example" : "43.781,566" 79 | }, 80 | "codigo_ibge" : { 81 | "type" : "string", 82 | "example" : "33" 83 | }, 84 | "nome" : { 85 | "type" : "string", 86 | "example" : "Rio de Janeiro" 87 | } 88 | } 89 | }, 90 | "CidadeInfo" : { 91 | "type" : "object", 92 | "properties" : { 93 | "area_km2" : { 94 | "type" : "string", 95 | "example" : "1200,179" 96 | }, 97 | "codigo_ibge" : { 98 | "type" : "string", 99 | "example" : "3304557" 100 | } 101 | } 102 | } 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /log.yaml: -------------------------------------------------------------------------------- 1 | version: 1 2 | formatters: 3 | simple: 4 | format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' 5 | 6 | handlers: 7 | info_file_handler: 8 | class: logging.handlers.RotatingFileHandler 9 | level: ERROR 10 | formatter: simple 11 | filename: /tmp/postmon-errors.log 12 | maxBytes: 10485760 13 | backupCount: 20 14 | encoding: utf-8 15 | 16 | loggers: 17 | __name__: 18 | level: ERROR 19 | handlers: [info_file_handler] 20 | propagate: no 21 | 22 | root: 23 | handlers: [info_file_handler] 24 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | nose==1.2.1 3 | nosexcover==1.0.10 4 | webtest==1.4.3 5 | mock==1.0.1 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | bottle==0.12.20 2 | bottle-healthcheck==0.2.1 3 | cssselect==1.0.3 4 | pymongo<3 5 | packtrack==1.6 6 | xmltodict 7 | flake8 8 | celery[mongodb]<4.0 9 | PyYAML==5.4 10 | requests==2.32.2 11 | raven==5.11.1 12 | newrelic==2.66.0.49 13 | unicode_slugify==0.1.3 14 | -------------------------------------------------------------------------------- /run.wsgi: -------------------------------------------------------------------------------- 1 | try: 2 | import newrelic.agent 3 | except ImportError: 4 | pass 5 | else: 6 | newrelic.agent.initialize() 7 | 8 | import logging.config 9 | import sys, os, bottle 10 | 11 | import yaml 12 | 13 | sys.path = ['/var/www/'] + sys.path 14 | os.chdir(os.path.dirname(__file__)) 15 | 16 | 17 | def _config_log(config_file): 18 | with open(config_file, 'rt') as f: 19 | config = yaml.load(f.read()) 20 | logging.config.dictConfig(config) 21 | 22 | 23 | log_file = os.getenv('POSTMON_LOGGING', 'log.yaml') 24 | _config_log(log_file) 25 | 26 | import PostmonServer 27 | 28 | application = bottle.default_app() 29 | -------------------------------------------------------------------------------- /test/assets/buscacepinter/01330000.json: -------------------------------------------------------------------------------- 1 | { 2 | "dados": [ 3 | { 4 | "bairro": "Bela Vista", 5 | "numeroLocalidade": "", 6 | "situacao": "", 7 | "locNu": "", 8 | "localidadeSubordinada": "", 9 | "cep": "01330000", 10 | "logradouroDNEC": "Rua Rocha", 11 | "locNoSem": "", 12 | "tipoCep": "2", 13 | "faixasCaixaPostal": [], 14 | "logradouroTextoAdicional": "", 15 | "logradouroTexto": "", 16 | "nomeUnidade": "", 17 | "uf": "SP", 18 | "localidade": "S\u00e3o Paulo", 19 | "baiNu": "", 20 | "faixasCep": [] 21 | } 22 | ], 23 | "total": 1, 24 | "erro": false, 25 | "mensagem": "DADOS ENCONTRADOS COM SUCESSO." 26 | } -------------------------------------------------------------------------------- /test/assets/buscacepinter/12245230.json: -------------------------------------------------------------------------------- 1 | { 2 | "dados": [ 3 | { 4 | "bairro": "Vila Bet\u00e2nia", 5 | "numeroLocalidade": "", 6 | "situacao": "", 7 | "locNu": "", 8 | "localidadeSubordinada": "", 9 | "cep": "12245230", 10 | "logradouroDNEC": "Avenida Tivoli - lado \u00edmpar", 11 | "locNoSem": "", 12 | "tipoCep": "2", 13 | "faixasCaixaPostal": [], 14 | "logradouroTextoAdicional": "", 15 | "logradouroTexto": "", 16 | "nomeUnidade": "", 17 | "uf": "SP", 18 | "localidade": "S\u00e3o Jos\u00e9 dos Campos", 19 | "baiNu": "", 20 | "faixasCep": [] 21 | } 22 | ], 23 | "total": 1, 24 | "erro": false, 25 | "mensagem": "DADOS ENCONTRADOS COM SUCESSO." 26 | } -------------------------------------------------------------------------------- /test/assets/buscacepinter/65930000.json: -------------------------------------------------------------------------------- 1 | { 2 | "dados": [ 3 | { 4 | "bairro": "", 5 | "numeroLocalidade": "", 6 | "situacao": "", 7 | "locNu": "", 8 | "localidadeSubordinada": "", 9 | "cep": "65930000", 10 | "logradouroDNEC": "", 11 | "locNoSem": "", 12 | "tipoCep": "1", 13 | "faixasCaixaPostal": [], 14 | "logradouroTextoAdicional": "", 15 | "logradouroTexto": "", 16 | "nomeUnidade": "", 17 | "uf": "MA", 18 | "localidade": "A\u00e7ail\u00e2ndia", 19 | "baiNu": "", 20 | "faixasCep": [] 21 | } 22 | ], 23 | "total": 1, 24 | "erro": false, 25 | "mensagem": "DADOS ENCONTRADOS COM SUCESSO." 26 | } -------------------------------------------------------------------------------- /test/assets/buscacepinter/69908768.json: -------------------------------------------------------------------------------- 1 | { 2 | "erro": false, 3 | "mensagem": "DADOS ENCONTRADOS COM SUCESSO.", 4 | "total": 1, 5 | "dados": [ 6 | { 7 | "uf": "AC", 8 | "localidade": "Rio Branco", 9 | "locNoSem": "", 10 | "locNu": "", 11 | "localidadeSubordinada": "", 12 | "logradouroDNEC": "Rodovia BR-364 (Rio Branco-Porto Velho) - at\u00e9 5014 - lado par", 13 | "logradouroTextoAdicional": "", 14 | "logradouroTexto": "", 15 | "bairro": "Loteamento Santa Helena", 16 | "baiNu": "", 17 | "nomeUnidade": "", 18 | "cep": "69908768", 19 | "tipoCep": "2", 20 | "numeroLocalidade": "", 21 | "situacao": "", 22 | "faixasCaixaPostal": [], 23 | "faixasCep": [] 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /test/assets/buscacepinter/75064590.json: -------------------------------------------------------------------------------- 1 | { 2 | "dados": [ 3 | { 4 | "bairro": "Vila Jayara", 5 | "numeroLocalidade": "", 6 | "situacao": "", 7 | "locNu": "", 8 | "localidadeSubordinada": "", 9 | "cep": "75064590", 10 | "logradouroDNEC": "Rua A - at\u00e9 69/70", 11 | "locNoSem": "", 12 | "tipoCep": "2", 13 | "faixasCaixaPostal": [], 14 | "logradouroTextoAdicional": "", 15 | "logradouroTexto": "", 16 | "nomeUnidade": "", 17 | "uf": "GO", 18 | "localidade": "An\u00e1polis", 19 | "baiNu": "", 20 | "faixasCep": [] 21 | }, 22 | { 23 | "bairro": "Vila Jayara", 24 | "numeroLocalidade": "", 25 | "situacao": "", 26 | "locNu": "", 27 | "localidadeSubordinada": "", 28 | "cep": "75064379", 29 | "logradouroDNEC": "Rua A - de 109/110 ao fim", 30 | "locNoSem": "", 31 | "tipoCep": "2", 32 | "faixasCaixaPostal": [], 33 | "logradouroTextoAdicional": "", 34 | "logradouroTexto": "", 35 | "nomeUnidade": "", 36 | "uf": "GO", 37 | "localidade": "An\u00e1polis", 38 | "baiNu": "", 39 | "faixasCep": [] 40 | } 41 | ], 42 | "total": 2, 43 | "erro": false, 44 | "mensagem": "ATEN\u00c7\u00c3O! O CEP 75064-590 FOI DESMEMBRADO CONFORME ABAIXO." 45 | } -------------------------------------------------------------------------------- /test/assets/buscacepinter/99999999.json: -------------------------------------------------------------------------------- 1 | { 2 | "dados": [], 3 | "total": 0, 4 | "erro": false, 5 | "mensagem": "DADOS NAO ENCONTRADOS" 6 | } -------------------------------------------------------------------------------- /test/database_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import unittest 4 | 5 | from database import MongoDb 6 | 7 | 8 | class MongoDbTest(unittest.TestCase): 9 | 10 | def setUp(self): 11 | self.db = MongoDb() 12 | 13 | self.db.insert_or_update({ 14 | 'cep': 'UNIQUE_KEY', 15 | 'logradouro': 'A', 16 | 'bairro': 'A', 17 | 'cidade': 'A', 18 | 'estado': 'A' 19 | }) 20 | 21 | def test_remove_empty_fields(self): 22 | 23 | ''' 24 | Quando um registro é atualizado no banco de dados, 25 | as chaves inexistentes devem ser removidas. 26 | ''' 27 | 28 | self.db.insert_or_update({ 29 | 'cep': 'UNIQUE_KEY', 30 | 'estado': 'B' 31 | }) 32 | 33 | result = self.db.get_one('UNIQUE_KEY') 34 | 35 | self.assertEqual(result['estado'], 'B') 36 | self.assertNotIn('logradouro', result) 37 | self.assertNotIn('bairro', result) 38 | self.assertNotIn('cidade', result) 39 | 40 | def tearDown(self): 41 | self.db.remove('UNIQUE_KEY') 42 | 43 | 44 | class UFTest(unittest.TestCase): 45 | uf_sp = { 46 | 'sigla': 'SP', 47 | 'codigo_ibge': '35', 48 | 'nome': u'São Paulo', 49 | } 50 | 51 | def setUp(self): 52 | self.db = MongoDb() 53 | self.db.insert_or_update_uf(self.uf_sp) 54 | 55 | def tearDown(self): 56 | self.db._db.ufs.remove() 57 | 58 | def test_get(self): 59 | result = self.db.get_one_uf_by_nome(u'São Paulo') 60 | for key, expected in self.uf_sp.items(): 61 | self.assertEqual(expected, result[key]) 62 | 63 | def test_update(self): 64 | self.db.insert_or_update_uf({ 65 | 'sigla': u'SP', 66 | 'codigo_ibge': '36' 67 | }) 68 | 69 | result = self.db.get_one_uf_by_nome(u'São Paulo') 70 | self.assertEqual('36', result['codigo_ibge']) 71 | self.assertEqual('SP', result['sigla']) 72 | 73 | 74 | class CidadeTest(unittest.TestCase): 75 | cidade_sp = { 76 | 'sigla_uf_nome_cidade': u'SP_SAO PAULO', 77 | 'area_km2': '1099', 78 | } 79 | 80 | def setUp(self): 81 | self.db = MongoDb() 82 | self.db.insert_or_update_cidade(self.cidade_sp) 83 | 84 | def tearDown(self): 85 | self.db._db.ufs.remove() 86 | 87 | def test_get(self): 88 | result = self.db.get_one_cidade(u'SP', u'São Paulo') 89 | for key, expected in self.cidade_sp.items(): 90 | self.assertEqual(expected, result[key]) 91 | 92 | def test_get_alt(self): 93 | result = self.db.get_one_cidade(u'SP', u'Outro lugar (São Paulo)') 94 | self.assertEqual('1099', result['area_km2']) 95 | 96 | def test_update(self): 97 | self.db.insert_or_update_cidade({ 98 | 'sigla_uf_nome_cidade': u'SP_SAO PAULO', 99 | 'area_km2': '2000', 100 | }) 101 | 102 | result = self.db.get_one_cidade(u'SP', u'São Paulo') 103 | self.assertEqual('2000', result['area_km2']) 104 | -------------------------------------------------------------------------------- /test/postmon_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from datetime import datetime, timedelta 4 | import json 5 | import re 6 | import unittest 7 | import mock 8 | 9 | import webtest 10 | import bottle 11 | from bson.objectid import ObjectId 12 | from packtrack import correios 13 | from requests import RequestException 14 | 15 | import CepTracker 16 | import PackTracker 17 | from PostmonServer import expired, jsonp_query_key 18 | from database import MongoDb 19 | 20 | bottle.DEBUG = True 21 | 22 | 23 | class PostmonBaseTest(object): 24 | 25 | expected = { 26 | '01330000': [{ 27 | 'logradouro': 'Rua Rocha', 28 | 'bairro': 'Bela Vista', 29 | 'cidade': u'São Paulo', 30 | 'estado': 'SP' 31 | }], 32 | '65930000': [{ 33 | 'cidade': u'Açailândia', 34 | 'estado': 'MA' 35 | }], 36 | '75064590': [{ 37 | 'logradouro': 'Rua A', 38 | 'bairro': 'Vila Jayara', 39 | 'cidade': u'Anápolis', 40 | 'estado': 'GO' 41 | }, { 42 | 'logradouro': 'Rua A', 43 | 'bairro': 'Vila Jayara', 44 | 'cidade': u'Anápolis', 45 | 'estado': 'GO' 46 | }], 47 | '12245230': [{ 48 | 'logradouro': u'Avenida Tivoli', 49 | 'complemento': u'lado ímpar', 50 | 'bairro': u'Vila Betânia', 51 | 'cidade': u'São José dos Campos', 52 | 'estado': 'SP' 53 | }], 54 | '69908768': [{ 55 | 'logradouro': 'Rodovia BR-364 (Rio Branco-Porto Velho)', 56 | 'complemento': u'até 5014 - lado par', 57 | 'bairro': 'Loteamento Santa Helena', 58 | 'cidade': 'Rio Branco', 59 | 'estado': 'AC' 60 | }], 61 | } 62 | 63 | def test_cep_com_rua(self): 64 | self.assertCep('01330000') 65 | 66 | def test_cep_sem_rua(self): 67 | self.assertCep('65930000') 68 | 69 | def test_cep_inexistente(self): 70 | self.assertCep('99999999') 71 | 72 | def test_cep_com_mais_de_um_resultado(self): 73 | self.assertCep('75064590') 74 | 75 | def test_ceps_com_complemento(self): 76 | self.assertCep('12245230') 77 | self.assertCep('69908768') 78 | 79 | 80 | class CepTrackerTest(unittest.TestCase, PostmonBaseTest): 81 | 82 | def setUp(self): 83 | self.tracker = CepTracker.CepTracker() 84 | 85 | def get_cep(self, cep): 86 | return self.tracker.track(cep) 87 | 88 | def assertCep(self, cep): 89 | 90 | result = self.get_cep(cep) 91 | expected = self.expected.get(cep) 92 | 93 | if not expected: 94 | self.assertTrue(result[0]['_meta'][CepTracker._notfound_key]) 95 | return 96 | 97 | self.assertEqual(len(expected), len(result)) 98 | 99 | for e, r in zip(expected, result): 100 | for key, value in e.items(): 101 | self.assertIn(key, r) 102 | self.assertEqual(value, r[key]) 103 | self.assertIn('_meta', r) 104 | self.assertIn('v_date', r['_meta']) 105 | 106 | 107 | class CepTrackerMockTest(CepTrackerTest): 108 | 109 | ''' 110 | O CepTrackerMockTest usa arquivos locais com os resultados 111 | obtidos nos Correios. Assim é possível saber se os testes do 112 | CepTrackerTest quebraram por problemas no código ou por alteração 113 | nos Correios. 114 | ''' 115 | 116 | def setUp(self): 117 | self.tracker = CepTracker.CepTracker() 118 | self.tracker._request = self._request_mock 119 | 120 | def _request_mock(self, cep): 121 | with open('test/assets/buscacepinter/' + cep + '.json') as f: 122 | return json.load(f) 123 | 124 | 125 | class PostmonWebTest(unittest.TestCase, PostmonBaseTest): 126 | 127 | ''' 128 | Teste do servidor do Postmon 129 | ''' 130 | 131 | def setUp(self): 132 | self.app = webtest.TestApp(bottle.app()) 133 | 134 | def get_cep(self, cep): 135 | response = self.app.get('/cep/' + cep) 136 | return response.json 137 | 138 | def assertCep(self, cep): 139 | expected = self.expected.get(cep) 140 | try: 141 | result = self.get_cep(cep) 142 | except webtest.AppError as ex: 143 | if not expected and '404' in ex.message and cep in ex.message: 144 | return 145 | raise ex 146 | 147 | for k, v in expected[0].items(): 148 | self.assertEqual(v, result[k]) 149 | 150 | self.assertNotIn('_meta', result) 151 | self.assertNotIn('v_date', result) 152 | 153 | 154 | class PostmonWebJSONPTest(PostmonWebTest): 155 | ''' 156 | Teste de requisições JSONP no servidor do Postmon 157 | ''' 158 | 159 | def setUp(self): 160 | self.jsonp_query_key = jsonp_query_key 161 | self.jsonp_func_name = 'func_name' 162 | super(PostmonWebJSONPTest, self).setUp() 163 | 164 | def get_cep(self, cep): 165 | response = self.app.get( 166 | '/cep/%s?%s=%s' % (cep, 167 | self.jsonp_query_key, 168 | self.jsonp_func_name)) 169 | 170 | regexp = re.compile(r'^%s\((.*)\);$' % self.jsonp_func_name) 171 | json_data = re.findall(regexp, response.body)[0] 172 | 173 | return json.loads(json_data) 174 | 175 | 176 | class PostmonV1WebTest(PostmonWebTest): 177 | 178 | ''' 179 | Teste do servidor do Postmon no /v1 180 | ''' 181 | @classmethod 182 | def setUpClass(cls): 183 | cls.db = MongoDb() 184 | cls.db.insert_or_update_uf({ 185 | 'sigla': 'SP', 186 | 'campo': 'valor', 187 | }) 188 | cls.db.insert_or_update_cidade({ 189 | 'sigla_uf_nome_cidade': u'SP_SAO PAULO', 190 | 'area_km2': '1099', 191 | }) 192 | 193 | @classmethod 194 | def tearDownClass(cls): 195 | cls.db._db.cidades.remove() 196 | cls.db._db.ufs.remove() 197 | 198 | def setUp(self): 199 | super(PostmonV1WebTest, self).setUp() 200 | 201 | def get_cep(self, cep): 202 | response = self.app.get('/v1/cep/' + cep) 203 | return response.json 204 | 205 | def test_uf(self): 206 | response = self.app.get('/v1/uf/sp') 207 | jr = json.loads(response.body) 208 | self.assertEqual({'campo': 'valor'}, jr) 209 | 210 | def test_uf_404(self): 211 | response = self.app.get('/v1/uf/xx', expect_errors=True) 212 | self.assertEqual('404 Estado xx nao encontrado', response.status) 213 | 214 | def test_cidade(self): 215 | response = self.app.get('/v1/cidade/SP/S%C3%83O PAULO') 216 | jr = json.loads(response.body) 217 | self.assertEqual({'area_km2': '1099'}, jr) 218 | 219 | def test_cidade_404(self): 220 | response = self.app.get('/v1/cidade/SP/XX', expect_errors=True) 221 | self.assertEqual('404 Cidade XX-SP nao encontrada', response.status) 222 | 223 | 224 | class PostmonXMLTest(unittest.TestCase): 225 | """ testa requisições XML """ 226 | 227 | def setUp(self): 228 | self.app = webtest.TestApp(bottle.app()) 229 | 230 | def get_cep(self, cep): 231 | response = self.app.get( 232 | '/cep/%s?format=xml' % cep 233 | ) 234 | return response 235 | 236 | def test_xml_return(self): 237 | import xmltodict 238 | response = self.get_cep('06708070') 239 | parsed = xmltodict.parse(response.body) 240 | result = parsed.get('result') 241 | self.assertEqual(result['bairro'], u'Parque S\xe3o George') 242 | self.assertEqual(result['cidade'], u'Cotia') 243 | self.assertEqual(result['cep'], u'06708070') 244 | self.assertEqual(result['estado'], u'SP') 245 | self.assertEqual(result['logradouro'], u'Avenida Eid Mansur') 246 | 247 | 248 | class PostmonOtherRoutesTest(unittest.TestCase): 249 | 250 | def setUp(self): 251 | self.app = webtest.TestApp(bottle.app()) 252 | 253 | def test_crossdomain(self): 254 | expected = bottle.template('crossdomain') 255 | response = self.app.get('/crossdomain.xml') 256 | self.assertMultiLineEqual(expected, response.body) 257 | 258 | 259 | class PostmonErrors(unittest.TestCase): 260 | 261 | def setUp(self): 262 | self.app = webtest.TestApp(bottle.app()) 263 | 264 | def get_cep(self, cep, format='json', expect_errors=False, use_v1=False): 265 | endpoint = '' 266 | if use_v1: 267 | endpoint += '/v1' 268 | endpoint += '/cep/%s' % cep 269 | if format != 'json': 270 | endpoint += '?format=' + format 271 | response = self.app.get(endpoint, expect_errors=expect_errors) 272 | return response 273 | 274 | @mock.patch('PostmonServer._get_info_from_source') 275 | def test_404_status(self, _mock): 276 | _mock.return_value = [] 277 | response = self.get_cep('99999999', expect_errors=True) 278 | self.assertEqual("404 CEP 99999999 nao encontrado", response.status) 279 | self.assertEqual('application/json', response.headers['Content-Type']) 280 | self.assertEqual('*', response.headers['Access-Control-Allow-Origin']) 281 | self.assertEqual('', response.body) 282 | 283 | @mock.patch('PostmonServer._get_info_from_source') 284 | def test_404_status_with_xml_format(self, _mock): 285 | _mock.return_value = [] 286 | response = self.get_cep('99999999', format='xml', expect_errors=True) 287 | self.assertEqual("404 CEP 99999999 nao encontrado", response.status) 288 | self.assertEqual('application/xml', response.headers['Content-Type']) 289 | self.assertEqual('*', response.headers['Access-Control-Allow-Origin']) 290 | self.assertEqual('', response.body) 291 | 292 | @mock.patch('PostmonServer._get_info_from_source') 293 | def test_503_status(self, _mock): 294 | _mock.side_effect = RequestException 295 | response = self.get_cep('88888888', expect_errors=True) 296 | self.assertEqual("503 Servico Temporariamente Indisponivel", 297 | response.status) 298 | self.assertEqual('application/json', response.headers['Content-Type']) 299 | self.assertEqual('*', response.headers['Access-Control-Allow-Origin']) 300 | self.assertEqual('', response.body) 301 | 302 | @mock.patch('PostmonServer._get_info_from_source') 303 | def test_503_status_with_xml_format(self, _mock): 304 | _mock.side_effect = RequestException 305 | response = self.get_cep('88888888', format='xml', expect_errors=True) 306 | self.assertEqual("503 Servico Temporariamente Indisponivel", 307 | response.status) 308 | self.assertEqual('application/xml', response.headers['Content-Type']) 309 | self.assertEqual('*', response.headers['Access-Control-Allow-Origin']) 310 | self.assertEqual('', response.body) 311 | 312 | def test_invalid_format(self): 313 | response = self.get_cep('99999999', format='xxx', expect_errors=True) 314 | self.assertEqual("400 Parametro format='xxx' invalido.", 315 | response.status) 316 | self.assertEqual('application/json', response.headers['Content-Type']) 317 | self.assertEqual('*', response.headers['Access-Control-Allow-Origin']) 318 | self.assertEqual('', response.body) 319 | 320 | @mock.patch('PostmonServer.Database') 321 | def test_404_cache_hit(self, _db): 322 | cep = '99999999' 323 | _db_instance = mock.Mock() 324 | _db.return_value = _db_instance 325 | _db_instance.get_one.return_value = { 326 | 'cep': cep, 327 | CepTracker._notfound_key: True, 328 | 'v_date': datetime.now(), 329 | } 330 | response = self.get_cep(cep, expect_errors=True) 331 | self.assertEqual("404 CEP %s nao encontrado" % cep, response.status) 332 | self.assertEqual('application/json', response.headers['Content-Type']) 333 | self.assertEqual('*', response.headers['Access-Control-Allow-Origin']) 334 | self.assertEqual('', response.body) 335 | _db_instance.get_one.assert_called_with(cep, fields={'_id': False}) 336 | 337 | def test_404_hard(self): 338 | response = self.get_cep("LETTERS", expect_errors=True) 339 | self.assertEqual('404 Not Found', response.status) 340 | 341 | 342 | class PostmonV1Errors(PostmonErrors): 343 | 344 | def get_cep(self, cep, format='json', expect_errors=False, use_v1=True): 345 | return super(PostmonV1Errors, self).get_cep(cep, format, 346 | expect_errors, use_v1) 347 | 348 | 349 | class TestExpired(unittest.TestCase): 350 | 351 | def test_empty(self): 352 | self.assertTrue(expired({})) 353 | 354 | def test_v_date_backward_compatibility(self): 355 | dt = datetime.now() - timedelta(weeks=5) 356 | obj = {'v_date': dt} 357 | self.assertFalse(expired(obj)) 358 | 359 | def test_v_date_expired_backward_compatibility(self): 360 | dt = datetime.now() - timedelta(weeks=54) 361 | obj = {'v_date': dt} 362 | self.assertTrue(expired(obj)) 363 | 364 | def test_meta_v_date(self): 365 | dt = datetime.now() - timedelta(weeks=5) 366 | obj = {'_meta': {'v_date': dt}} 367 | self.assertFalse(expired(obj)) 368 | 369 | def test_meta_v_date_expired(self): 370 | dt = datetime.now() - timedelta(weeks=54) 371 | obj = {'_meta': {'v_date': dt}} 372 | self.assertTrue(expired(obj)) 373 | 374 | def test_notfound(self): 375 | dt = datetime.now() - timedelta(weeks=2) 376 | obj = {'_meta': {'v_date': dt, CepTracker._notfound_key: True}} 377 | self.assertFalse(expired(obj)) 378 | 379 | def test_notfound_expired_early(self): 380 | dt = datetime.now() - timedelta(weeks=5) 381 | obj = {'_meta': {'v_date': dt, CepTracker._notfound_key: True}} 382 | self.assertTrue(expired(obj)) 383 | 384 | 385 | class TestDatabase(unittest.TestCase): 386 | def test_insert_notfound(self): 387 | db = MongoDb() 388 | cep = u'11111111' 389 | db.remove(cep) 390 | db.insert_or_update({ 391 | u'cep': cep, 392 | u'_meta': { 393 | u'v_date': 'v_date', 394 | CepTracker._notfound_key: True, 395 | } 396 | }) 397 | expected = { 398 | u'cep': cep, 399 | u'estado': u'SP', 400 | u'_meta': { 401 | u'v_date': 'v_date', 402 | } 403 | } 404 | db.insert_or_update(expected) 405 | result = db.get_one(cep, fields={'_id': False}) 406 | self.assertEqual(expected, result) 407 | 408 | 409 | class PackTrackTest(unittest.TestCase): 410 | 411 | def setUp(self): 412 | db = MongoDb() 413 | self.collection = db.packtrack._collection 414 | self.app = webtest.TestApp(bottle.app()) 415 | 416 | def tearDown(self): 417 | self.collection.remove() 418 | 419 | def _get(self, track, provider='ect', expect_errors=False): 420 | url = '/v1/rastreio/{}/{}'.format(provider, track) 421 | response = self.app.get(url, expect_errors=expect_errors) 422 | if expect_errors: 423 | return response 424 | 425 | jr = json.loads(response.body) 426 | return jr 427 | 428 | def _post(self, track, data): 429 | url = '/v1/rastreio/ect/' + track 430 | response = self.app.post(url, json.dumps(data), 431 | headers={'Content-Type': 'application/json'}) 432 | jr = json.loads(response.body) 433 | return jr 434 | 435 | @mock.patch('PackTracker.correios') 436 | def test_get(self, _mock): 437 | data = [{ 438 | "codigo": "test", 439 | "servico": "ect", 440 | "historico": [{ 441 | "detalhes": None, 442 | "local": "AGF SAO PATRICIO - Sao Paulo/SP", 443 | "data": "19/07/2016 11:37", 444 | "situacao": "Postado" 445 | }] 446 | }] 447 | _mock.return_value = data[0]["historico"] 448 | response = self._get("test") 449 | self.assertEqual(data[0], response) 450 | 451 | @mock.patch('PackTracker.correios') 452 | def test_get_404(self, _mock): 453 | _mock.side_effect = AttributeError 454 | response = self._get("test", expect_errors=True) 455 | self.assertEqual('404 Pacote test nao encontrado', response.status) 456 | 457 | def test_get_another_provider(self): 458 | response = self._get("test", provider="google", expect_errors=True) 459 | self.assertEqual('404 Servico google nao encontrado', response.status) 460 | 461 | def test_register_packtrack(self): 462 | data = { 463 | 'callback': 'http://example.com', 464 | } 465 | response = self._post('test', data) 466 | self.assertTrue(response['token']) 467 | 468 | def test_register_same_packtrack(self): 469 | data = [{ 470 | 'callback': 'http://example.com', 471 | 'something': 'XXX', 472 | }, { 473 | 'callback': 'http://example.com', 474 | 'something': 'YYY', 475 | }] 476 | response = self._post('test', data[0]) 477 | token = response['token'] 478 | 479 | response = self._post('test', data[1]) 480 | self.assertEqual(token, response['token']) 481 | 482 | obj = self.collection.find_one(ObjectId(token)) 483 | self.assertEqual(data, obj['_meta']['callbacks']) 484 | 485 | def test_register_same_callback(self): 486 | data = { 487 | 'callback': 'http://example.com', 488 | 'something': 'XXX', 489 | } 490 | response = self._post('test', data) 491 | token = response['token'] 492 | response = self._post('test', data) 493 | 494 | obj = self.collection.find_one(ObjectId(token)) 495 | self.assertEqual([data], obj['_meta']['callbacks']) 496 | 497 | @mock.patch('PackTracker.correios') 498 | def test_run(self, _mock): 499 | _mock.return_value = [{ 500 | "detalhes": None, 501 | "local": "AGF SAO PATRICIO - Sao Paulo/SP", 502 | "data": "19/07/2016 11:37", 503 | "situacao": "Postado" 504 | }] 505 | data = { 506 | 'callback': 'http://example.com', 507 | 'something': 'XXX', 508 | } 509 | self._post('test', data) 510 | changed = PackTracker.run('ect', 'test') 511 | self.assertTrue(changed) 512 | 513 | self._post('test', data) 514 | changed = PackTracker.run('ect', 'test') 515 | self.assertFalse(changed) 516 | 517 | _mock.return_value.append({ 518 | "detalhes": "Encaminhado para UNIDADE DE CORREIOS/BR", 519 | "local": "AGF SAO PATRICIO - Sao Paulo/SP", 520 | "data": "20/07/2016 08:46", 521 | "situacao": "Encaminhado" 522 | }) 523 | self._post('test', data) 524 | changed = PackTracker.run('ect', 'test') 525 | self.assertTrue(changed) 526 | 527 | self._post('test', data) 528 | changed = PackTracker.run('ect', 'test') 529 | self.assertFalse(changed) 530 | 531 | @mock.patch('PackTracker.requests.post') 532 | def test_report(self, _mock_requests): 533 | 534 | input_data = { 535 | 'callback': 'http://example.com', 536 | 'something': 'XXX', 537 | } 538 | response = self._post('test', input_data) 539 | token = response['token'] 540 | 541 | encomenda = correios.Encomenda('track') 542 | status = correios.Status( 543 | local="AGF SAO PATRICIO - Sao Paulo/SP", 544 | data="19/07/2016 11:37", 545 | situacao="Postado", 546 | ) 547 | encomenda.adicionar_status(status) 548 | with mock.patch('PackTracker.packtrack') as _mock_correios: 549 | _mock_correios.Correios.track.return_value = encomenda 550 | changed = PackTracker.run('ect', 'test') 551 | self.assertTrue(changed) 552 | 553 | PackTracker.report('ect', 'test') 554 | 555 | call = _mock_requests.call_args 556 | self.assertEqual(('http://example.com',), call[0]) 557 | 558 | data = json.loads(call[1]['data']) 559 | 560 | self.assertEqual(input_data, data['input']) 561 | self.assertEqual(token, data['token']) 562 | self.assertEqual([{ 563 | u'detalhes': status.detalhes, 564 | u'local': status.local, 565 | u'situacao': status.situacao, 566 | u'data': status.data, 567 | }], data['historico']) 568 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import bottle 2 | from slugify import slugify 3 | 4 | 5 | def slug(value): 6 | value = slugify(value, only_ascii=True, spaces=True) 7 | return value.upper() 8 | 9 | 10 | class EnableCORS(object): 11 | name = 'enable_cors' 12 | api = 2 13 | 14 | def apply(self, fn, context): 15 | def _enable_cors(*args, **kwargs): 16 | # set CORS headers 17 | bottle.response.headers.update({ 18 | 'Access-Control-Allow-Origin': '*', 19 | 'Access-Control-Allow-Methods': 'GET, POST, PUT, OPTIONS', 20 | 'Access-Control-Allow-Headers': 21 | ', '.join(bottle.request.headers.keys()) 22 | }) 23 | if bottle.request.method != 'OPTIONS': 24 | # actual request; reply with the actual response 25 | return fn(*args, **kwargs) 26 | 27 | return _enable_cors 28 | -------------------------------------------------------------------------------- /views/crossdomain.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | --------------------------------------------------------------------------------