Firts upload

This commit is contained in:
Antonio de la Rosa 2025-11-30 00:02:13 +01:00
commit fae5555503
184 changed files with 19239 additions and 0 deletions

8
.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
*~
*.pyc
__pycache__
modules/*
!modules/welcome
!modules/admin
themes/*
!themes/default/

3
.gitmodules vendored Normal file
View file

@ -0,0 +1,3 @@
[submodule "cuchulu/modules/admin/media/js/jsutils"]
path = cuchulu/modules/admin/media/js/jsutils
url = https://git.cuchulu.com/paramecio/jsutils.git

661
LICENSE.txt Normal file
View file

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

8
MANIFEST.in Normal file
View file

@ -0,0 +1,8 @@
include cuchulu/*.py
include README.md
include LICENSE
include REQUIREMENTS
recursive-include cuchulu/libraries *
recursive-include cuchulu/frontend *
recursive-include cuchulu/settings *
recursive-include cuchulu/modules *

64
README.md Normal file
View file

@ -0,0 +1,64 @@
# A simple webframework based in Bottle and Mako for create nice webapps
# Installation
This guide give you step by step for install cuchulu sucessfully.
## Requirements
For install Paramecio you need a server preferably with GNU/Linux installed. Paramecio is tested normally in Debian derivated how Ubuntu, and Red hat derivated distros how Centos or Fedora but should work fine in FreeBSD, MacOSX and other *nix like operating systems.
Also, you need the next software installed in your os:
### Python 3.4 or later.
Paramecio should work fine since python 3.6 but is tested in 3.12 and 3.13 python 3 versions.
In Debian and Ubuntu you can install Python 3 using the next command: `apt-get install python3`.
In Fedora and other Red Hat derived distros you can use `dnf install python3`.
### MySQL or MariaDB database servers.
MariaDB 10.6 and later are recommended.
In Debian and Ubuntu you can install MariaDB using the next command: `apt-get install mariadb-server`.
In Fedora and other Red Hat derived distros you can use `dnf install mariadb-server`.
### Pip
Pip is the package manager of python. You can use the package manager of your os for get python dependencies packages but in my experience is better install the packages directly with pip.
In Debian and Ubuntu you can install pip using the next command: `apt-get install python3-pip`.
In Fedora and other Red Hat derived distros you can use `dnf install python3-pip`.
### Git
[Git](https://git-scm.com/) is a tool used for manage source code repositories. Also is a tool that can be used for distribute software. For install the next tools you need git installed in your server.
In Debian and Ubuntu you can install git using the next command: `apt-get install git`.
In Fedora and other Red Hat derived distros you can use `dnf install git`.
## Install Paramecio Framework
You can install the framework using the next command in your server:
`pip3 install cuchulu`
or if you want development version:
`pip3 install git+https://bitbucket.org/cuchulu/cuchulufm`
This command will install in your server cuchulu framework with its dependencies.
When Paramecio finish the installing, you can create your first cuchulu site with `cuchulu` command.
### Tipical errors
If you get an error in your installation of dependencies how MarkupSafe or SqlAlchemy, please install gcc or install manually mako and sqlalchemy with your system package manager. For example, for debian and ubuntu:
`apt-get install python3-mako python3-sqlalchemy` and try pip3 command again.

5
README.rst Normal file
View file

@ -0,0 +1,5 @@
==========================================================
Paramecio is a simple framework based in bottle and mako.
==========================================================

8
REQUIREMENTS Normal file
View file

@ -0,0 +1,8 @@
# REQUIREMENTS
- Python >3.11
- Bottle 0.12+
- Mako
Use PIP is recommended for new installations.

6
TESTS Normal file
View file

@ -0,0 +1,6 @@
# Tests execution
For execute the tests you can use this command:
python3 -m unittest PYTHON_PATH/cuchulu/tests/nameoftest.py

0
cuchulu/__init__.py Normal file
View file

5
cuchulu/__main__.py Normal file
View file

@ -0,0 +1,5 @@
from cuchulu.console import start
if __name__=="__main__":
start()

263
cuchulu/app.py Normal file
View file

@ -0,0 +1,263 @@
import os, sys, traceback, inspect, resource
from importlib import import_module
from bottle import route, get, post, run, default_app, abort, request, response, static_file, load, hook, error, debug, redirect, template
from settings import config
#from beaker.middleware import SessionMiddleware
from mimetypes import guess_type
from cuchulu.libraries.db.webmodel import WebModel
from cuchulu.libraries.datetime import set_timezone
#from itsdangerous import JSONWebSignatureSerializer
from cuchulu.libraries.keyutils import create_key_encrypt, create_key_encrypt_256, create_key
from cuchulu.wsgiapp import app
#from cuchulu.libraries.sessions import after_session
modules_pass=False
#app.reset()
#from cuchulu.libraries.sessions import generate_session
#Prepare links for static.
#WARNING: only use this feature in development, not in production.
#def create_app():
workdir=os.getcwd()
arr_module_path={}
if config.session_enabled==True:
#Create dir for sessions
if 'session.data_dir' in config.session_opts:
if not os.path.isdir(config.session_opts['session.data_dir']):
os.makedirs(config.session_opts['session.data_dir'], 0o700, True)
"""
@app.hook('after_request')
def clean_session():
after_session()
"""
error_reporting=False
if hasattr(config, 'error_reporting'):
error_reporting=config.error_reporting
def prepare_app():
# In mod_wsgi, make strange thing with reloading.
app.reset()
def print_memory():
print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
routes={}
module_loaded=None
#Getting paths for loaded modules for use in media load files
"""
for module in config.modules:
#controller_path=sys.modules[module]
controller_base=sys.modules[module].__path__[0]
base_module=module.split('.')[-1]
arr_module_path[base_module]=controller_base
"""
#app.add_hook('before_request', print_memory)
"""
for added_app in config.apps:
a=import_module(added_app)
#print(added_app, file=sys.stdout)
app_name=getattr(a, config.apps[added_app][0])
app.mount(config.apps[added_app][1], app_name)
#print(added_app)
#print(a.__path__[0])
"""
app_mounts={}
for key_app, added_app in config.apps.items():
controller_path=import_module(added_app[0])
controller_base=os.path.dirname(controller_path.__file__)
#print(controller_base)
dir_controllers=os.listdir(controller_base)
for controller in dir_controllers:
if controller.endswith('.py') and controller.find('__init__')==-1:
controller_py=controller.replace('.py', '')
module_app=added_app[0]+'.'+controller_py
a=import_module(module_app)
if added_app[1]!='':
if controller_py=='app':
app_name=getattr(a, added_app[1])
app_mounts[added_app[2]]=app_name
arr_module_path[key_app]=os.path.dirname(sys.modules[module_app].__file__)
for k_app,v_app in app_mounts.items():
#print(k_app)
if k_app!='/':
app.mount(k_app, v_app)
elif k_app!='':
app.merge(v_app)
set_timezone()
if error_reporting:
from cuchulu.libraries.error_reporting import ErrorReportingPlugin
app.install(ErrorReportingPlugin())
if hasattr(config, 'plugins_app'):
for p in config.plugins_app:
app.install(p())
# Clean last slash
@app.hook('before_request')
def strip_path():
request.environ['PATH_INFO'] = request.environ['PATH_INFO'].rstrip('/')
# Set error screen if not debug setted
if config.debug==False:
@app.error(404)
def error404(error):
return 'Error: page not found'
debug(config.debug)
#Prepare app
application=app
# Load modules
try:
#from settings import modules
prepare_app()
except:
app.reset()
@app.route('/')
def catch_errors(all='/'):
try:
from pathlib import Path
#from settings import modules
import time
prepare_app()
p=Path('app.py')
p.touch()
time.sleep(1)
except:
raise
redirect(request.url)
catch_errors=app.route('/<all:path>')(catch_errors)
# Prepare static routes
if config.yes_static==True:
@app.route('/media/<filename:path>')
def send_static(filename):
mimetype=guess_type(workdir+'/themes/'+config.theme+'/media/'+filename)
return static_file(filename, root=workdir+'/themes/'+config.theme+'/media/', mimetype=mimetype[0])
#def add_func_static_module(module):
@app.route('/mediafrom/<module>/<filename:path>')
def send_static_module(module, filename):
path_module=arr_module_path[module]+'/media/'
file_path_module=path_module+filename
path=workdir+'/themes/'+config.theme+'/media/'+module
file_path=path+'/'+filename
if os.path.isfile(file_path):
mimetype=guess_type(path+'/'+filename)
return static_file(filename, root=path, mimetype=mimetype[0])
else:
mimetype=guess_type(path_module+'/'+filename)
return static_file(filename, root=path_module, mimetype=mimetype[0])
def error_handler_500(e):
tpl_error="""
%try:
%from bottle import DEBUG, request
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>Error: {{e.status}}</title>
<style type="text/css">
html {background-color: #e8eff0; font-family: sans;}
body {background-color: #fbfbfb; border: 1px solid #ddd;
padding: 15px; margin: 15px;}
pre {background-color: #e0f6fa; border: 1px solid #ddd; padding: 5px;}
</style>
</head>
<body>
<h1>Error: {{e.status}}</h1>
<p>Sorry, the requested URL <tt>{{repr(request.url)}}</tt>
caused an error:</p>
<pre>{{e.body}}</pre>
%if DEBUG and e.exception:
<h2>Exception:</h2>
%try:
%exc = repr(e.exception)
%except:
%exc = '<unprintable %s object>' % type(e.exception).__name__
%end
<pre>{{exc}}</pre>
%end
%if DEBUG and e.traceback:
<h2>Traceback:</h2>
<pre>{{e.traceback}}</pre>
%end
</body>
</html>
%except ImportError:
<b>ImportError:</b> Could not generate the error page. Please add bottle to
the import path.
%end
"""
return template(tpl_error, e=e)
app.error(code=500, callback=error_handler_500)
def run_app(app):
if config.server_used!='cherrypy':
run(app=app, host=config.host, server=config.server_used, port=config.port, debug=config.debug, reloader=config.reloader)
else:
from cuchulu.cherry import run_cherrypy_server
run_cherrypy_server()

72
cuchulu/cherry.py Normal file
View file

@ -0,0 +1,72 @@
# Import your application as:
# from wsgi import application
# Example:
from index import application
from settings import config
# Import CherryPy
import cherrypy
def run_cherrypy_server():
access_log=''
error_log=''
if hasattr(config, 'access_log'):
access_log=config.access_log
if hasattr(config, 'error_log'):
error_log=config.error_log
cherrypy.config.update({'engine.autoreload.on': config.reloader, 'log.access_file': access_log, 'log.error_file': error_log})
# Mount the application
cherrypy.tree.graft(application, "/")
# Unsubscribe the default server
cherrypy.server.unsubscribe()
# Instantiate a new server object
server = cherrypy._cpserver.Server()
# Configure the server object
server.socket_host=config.host
server.socket_port=config.port
server.thread_pool=10
if hasattr(config, 'thread_pool'):
server.thread_pool=config.thread_pool
# For SSL Support
# By default use pyopenssl
server.ssl_module='pyopenssl'
if hasattr(config, 'ssl_module'):
server.ssl_module=config.ssl_module
if hasattr(config, 'ssl_certificate') and hasattr(config, 'private_key') and hasattr(config, 'certificate_chain'):
server.ssl_certificate=config.ssl_certificate
server.ssl_private_key=config.ssl_private_key
server.ssl_certificate_chain=config.certificate_chain
# Subscribe this server
server.subscribe()
# Example for a 2nd server (same steps as above):
# Remember to use a different port
# server2 = cherrypy._cpserver.Server()
# server2.socket_host = "0.0.0.0"
# server2.socket_port = 8081
# server2.thread_pool = 30
# server2.subscribe()
# Start the server engine (Option 1 *and* 2)
cherrypy.engine.start()
cherrypy.engine.block()

431
cuchulu/console.py Normal file
View file

@ -0,0 +1,431 @@
#!/usr/bin/env python3
import argparse
import os
import shutil
import getpass
import re
from pathlib import Path
from base64 import b64encode
from cuchulu.libraries.db.webmodel import WebModel
from cuchulu.modules.admin2.models.admin import UserAdmin2, LoginTries2
from subprocess import call
from urllib.parse import urlparse
def start():
parser=argparse.ArgumentParser(prog='cuchulu', description='A tool for create new cuchulu sites')
parser.add_argument('--path', help='The path where the cuchulu site is located', required=True)
parser.add_argument('--modules', help='A list separated by commas with the git repos for download modules for this site', required=False)
parser.add_argument('--symlink', help='Set if create direct symlink to cuchulu in new site', action='store_true')
parser.add_argument('--tests', help='Create a symlink to tests for check into cuchulu site', action='store_true')
# Options for deploy
parser.add_argument('--url', help='The http/https base url of the real proxy server. Example: https://www.exampledomain.com, default is http://localhost:8080', required=False)
parser.add_argument('--folder', help='If you deploy in a subdirectory, set it, without beggining and ending slashes', required=False)
parser.add_argument('--host', help='The host ip or domain where the app is binded', required=False)
parser.add_argument('--port', help='Change the default port 8080 to other number. Use 80 is not recommended, use 80 for the proxy server how nginx or apache', required=False)
args=parser.parse_args()
#print(args)
#exit(0)
workdir=os.path.dirname(os.path.abspath(__file__))
# Create directory
path=Path(args.path)
try:
path.mkdir(0o755, True)
except:
print('Error: cannot create the directory. Check if exists and if you have permissions')
exit()
# Create folder settings and copy app.py, admin.py
path_settings=args.path+'/settings'
try:
os.mkdir(path_settings, 0o755)
except:
print('Error: cannot create the directory. Check if exists and if you have permissions')
# Copy the files. Need optimization, use an array for save the filenames and a simple for loop.
try:
shutil.copy(workdir+'/settings/config.py.sample', path_settings+'/config.py')
except:
print('Error: cannot copy the file config.py. Check if exists and if you have permissions for this task')
try:
shutil.copy(workdir+'/frontend/app.py', args.path+'/app.py')
except:
print('Error: cannot copy the file app.py. Check if exists and if you have permissions for this task')
try:
shutil.copy(workdir+'/frontend/padmin.py', args.path+'/padmin.py')
except:
print('Error: cannot copy the file padmin.py. Check if exists and if you have permissions for this task')
try:
shutil.copy(workdir+'/frontend/i18nadmin.py', args.path+'/i18nadmin.py')
except:
print('Error: cannot copy the file i18nadmin.py. Check if exists and if you have permissions for this task')
try:
shutil.copy(workdir+'/frontend/regenerate.py', args.path+'/regenerate.py')
except:
print('Error: cannot copy the file regenerate.py. Check if exists and if you have permissions for this task')
try:
shutil.copy(workdir+'/frontend/create_module.py', args.path+'/create_module.py')
except:
print('Error: cannot copy the file create_module.py. Check if exists and if you have permissions for this task')
"""
try:
shutil.copy(workdir+'/settings/modules.py', path_settings+'/modules.py')
except:
print('Error: cannot copy the file modules.py. Check if exists and if you have permissions for this task')
"""
if args.symlink==True:
try:
os.symlink(workdir, args.path+'/cuchulu', True)
except:
print('Error: cannot symlink cuchulu in new site')
if args.tests==True:
try:
os.symlink(workdir, args.path+'/cuchulu/', True)
except:
print('Error: cannot symlink cuchulu in new site')
with open(path_settings+'/config.py', 'r') as f:
conf=f.read()
random_bytes = os.urandom(24)
secret_key_session = b64encode(random_bytes).decode('utf-8').strip()
conf=conf.replace('im smoking fool', secret_key_session)
#domain='localhost'
#conf=conf.replace("domain='localhost'", "domain='"+args.url+"'")
if args.host==None:
args.host='localhost'
conf=conf.replace("host='localhost'", "host='"+args.host+"'")
if args.port==None:
args.port='8080'
conf=conf.replace("port=8080", "port="+args.port)
base_url='/'
if args.folder==None:
args.folder=''
else:
#args.folder='/'+args.folder
base_url='/'+args.folder+'/'
conf=conf.replace("base_url='/'", "base_url='"+base_url+"'")
if args.url==None:
args.url='http://localhost:8080'
domain_url=args.url
conf=conf.replace("domain_url='http://localhost:8080'", "domain_url='"+domain_url+"'")
#domain_url='http://localhost:8080'
with open(path_settings+'/config.py', 'w') as f:
f.write(conf)
# Question about mysql configuration? If yes, install configuration
s=input('Do you want use cuchulu with MySQL database? y/n: ')
if s=='y' or s=='Y':
host_db=input('MySQL database server host, by default localhost: ').strip()
db=input('MySQL database name, by default cuchulu_db: ').strip()
user_db=input('MySQL database user, by default root: ').strip()
pass_db=getpass.getpass('MySQL database password, by default "": ').strip()
if host_db=='':
host_db='localhost'
if user_db=='':
user_db='root'
#user=UserAdmin()
#Create db
if db=="":
db='cuchulu_db'
WebModel.connections={'default': {'name': 'default', 'host': host_db, 'user': user_db, 'password': pass_db, 'db': '', 'charset': 'utf8mb4', 'set_connection': False, 'db_type': 'pymysql'} }
connection_code="WebModel.connections={'default': {'name': 'default', 'host': '"+host_db+"', 'user': '"+user_db+"', 'password': '"+pass_db+"', 'db': '"+db+"', 'charset': 'utf8mb4', 'set_connection': False, 'db_type': 'pymysql'} }"
with open(path_settings+'/config.py', 'a') as f:
f.write("\n\n"+connection_code)
f.close()
sql='create database '+db
conn=WebModel.connection()
useradmin=UserAdmin2(conn)
logintries=LoginTries2(conn)
# Check if db exists
c=0
with useradmin.query('SHOW DATABASES LIKE "%s"' % db) as cur:
c=cur.rowcount
if c==0:
useradmin.query(sql)
#print('Error: cannot create database or db doesn\'t exists, check database permissions for this user')
#if not useradmin.query(sql):
#print('Error: cannot create database, check the data of database')
#else:
useradmin.query('use '+db)
admin=input('Do you want create admin site? y/n: ')
if admin=='y' or admin=='Y':
try:
#shutil.copy(workdir+'/settings/modules.py.admin', path_settings+'/modules.py')
#shutil.copy(workdir+'/settings/config_admin.py.sample', path_settings+'/config_admin.py')
sql=useradmin.create_table()
tries_sql=logintries.create_table()
if not useradmin.query(sql) or not useradmin.query(tries_sql) :
print('Error: cannot create table admin, you can create this table with padmin.py')
else:
# Add admin module to config
with open(path_settings+'/config.py', 'r') as f:
config_text=f.read()
f.close()
#config_text=config_text.replace("modules=['cuchulu.modules.welcome']", "modules=['cuchulu.modules.welcome', 'cuchulu.modules.lang']")
config_text=config_text.replace("apps={'welcome': ['cuchulu.modules.welcome', 'welcome_app', '/'], 'lang': ['cuchulu.modules.lang', '', '']}", "apps={'welcome': ['cuchulu.modules.welcome', 'welcome_app', '/'], 'lang': ['cuchulu.modules.lang', '', ''], 'admin2': ['cuchulu.modules.admin2', 'admin_app', '/admin/']}")
with open(path_settings+'/config.py', 'w') as f:
f.write(config_text)
f.close()
try:
shutil.copy(workdir+'/settings/modules.py.admin', path_settings+'/modules.py')
except:
print('Error: cannot copy the file modules.py. Check if exists and if you have permissions for this task')
print('Created admin site...')
except:
print('Error: cannot create the database. Check if tables exists in it and if you have permissions for this task')
exit(1)
pass
# Install modules
if args.modules!=None:
if args.modules.strip()!='':
arr_modules=args.modules.split(',')
final_modules=[]
final_modules_models=[]
if len(arr_modules)>0:
for k, module in enumerate(arr_modules):
module=module.strip()
try:
u=urlparse(module)
module_path=os.path.basename(u.path)
except:
print('Error: not valid url for repository')
exit(1)
if call("git clone %s %s/modules/%s" % (module, path, module_path), shell=True) > 0:
print('Error, cannot install the module %s' % module_path)
exit(1)
else:
print('Added module %s' % module_path)
final_modules.append(("modules/%s" % (module_path)).replace('/', '.'))
final_modules_models.append("modules/%s" % (module_path))
# Edit config.py
with open(path_settings+'/config.py') as f:
modules_final='\''+'\', \''.join(final_modules)+'\''
p=re.compile(r"^modules=\[(.*)\]$")
#config_file=p.sub(r"modules=[\1, "+modules_final+"]", "modules=['cuchulu.modules.welcome', 'cuchulu.modules.admin', 'cuchulu.modules.lang', 'modules.pastafari', 'modules.monit', 'modules.example']")
final_config=''
for line in f:
if p.match(line):
line=p.sub(r"modules=[\1, "+modules_final+"]", line)
final_config+=line
with open(path_settings+'/config.py', 'w') as f:
f.write(final_config)
print('Updated configuration for add new modules...')
#Change workdir
real_dir=os.getcwd()
os.chdir(args.path)
#Regenerating modules.py
"""
regenerate='regenerate.py'
os.chmod(regenerate, 0o755)
if call('./regenerate.py', shell=True) > 0:
print('Error, cannot regenerate the modules.py script')
exit(1)
else:
print('Regeneration of modules.py finished')
"""
# Installing models
padmin='padmin.py'
os.chmod(padmin, 0o755)
for mod_path in final_modules_models:
models_path=mod_path+'/models'
if os.path.isdir(models_path):
models_files=os.listdir(models_path)
m=re.compile(r".*\.py$")
underscore=re.compile("^__.*")
for f in models_files:
if m.match(f) and not underscore.match(f):
if call('./padmin.py --model '+models_path+'/'+f, shell=True) > 0:
print('Error, cannot create the modules of '+models_path+'/'+f)
else:
print('Models from '+models_path+'/'+f+' created')
# Execute two times the loop because i can need good installed models for postscript script
# Execute postscript
print('Executing postscripts')
for mod_path in final_modules_models:
postscript=mod_path+"/install/postinstall.py"
os.chmod(padmin, 0o755)
if os.path.isfile(postscript):
os.chmod(postscript, 0o755)
if call('./'+postscript, shell=True) > 0:
print('Error, cannot execute the postinstall script')
exit(1)
else:
print('Postinstall script finished')
conn.close()
if __name__=="__main__":
start()

160
cuchulu/create_module.py Normal file
View file

@ -0,0 +1,160 @@
#!/usr/bin/env python3
import traceback
import argparse
import os,sys
import shutil
import getpass
from pathlib import Path
from settings import config
from importlib import import_module
import re
def start():
"""Module for create new modules for cuchulu
"""
parser=argparse.ArgumentParser(description='A tool for create new modules for cuchulu')
parser.add_argument('--path', help='The path where the new cuchulu module is located', required=True)
args=parser.parse_args()
workdir=os.path.dirname(os.path.abspath(__file__))
# Create directory
path=Path('modules/'+args.path)
try:
path.mkdir(0o755, True)
open('modules/'+args.path+'/__init__.py', 'a').close()
except:
print('Error: cannot create the directory. Check if exists and if you have permissions')
exit(1)
#Create base controller file
#f=open('modules/'+args.path+'/index.py', 'w')
name_module=os.path.basename(args.path)
try:
shutil.copy(workdir+'/examples/app.py', 'modules/'+args.path)
with open('modules/'+args.path+'/app.py') as f:
app_file=f.read()
app_file=app_file.replace('/example', '/'+name_module)
with open('modules/'+args.path+'/app.py', 'w') as f:
f.write(app_file)
pass
except:
print('Error: cannot copy controller example. Check if you have permissions')
exit(1)
# Edit config.py
#module_final='modules.'+name_module
module_final=f"'{name_module}': ['modules.{name_module}', '', '']"
try:
with open('./settings/config.py') as f:
#modules_final='\''+'\', \''.join(final_modules)+'\''
p=re.compile(r"^apps=\{(.*)\}$")
#config_file=p.sub(r"modules=[\1, "+modules_final+"]", "modules=['cuchulu.modules.welcome', 'cuchulu.modules.admin', 'cuchulu.modules.lang', 'modules.pastafari', 'modules.monit', 'modules.example']")
final_config=''
for line in f:
if p.match(line):
line=p.sub(r"apps={\1, "+module_final+"}", line)
final_config+=line
with open('./settings/config.py', 'w') as f:
f.write(final_config)
print('Updated configuration for add new modules...')
except:
print('Cannot update configuration, you need add the new module by hand')
# Reload config
#config.modules.append(module_final)
# Regenerate modules
#regenerate_modules_config()
def regenerate_modules_config():
print("Regenerating modules configuration...")
modules=[]
modules.append("#!/usr/bin/env python3\n\n")
modules.append("list_modules=[]\n\n")
for module in config.modules:
try:
controller_path=import_module(module)
controller_base=os.path.dirname(controller_path.__file__)
base_module=module.split('.')[-1]
dir_controllers=os.listdir(controller_base)
modules.append('from '+module+' import ')
arr_controllers=[]
for controller in dir_controllers:
if controller.find('.py')!=-1 and controller.find('_')==-1:
controller_py=controller.replace('.py', '')
arr_controllers.append(controller_py)
#load(module+'.'+controller_py)
modules.append(", ".join(arr_controllers))
modules.append("\n\n")
#add_func_static_module(controller_base)
except:
print("Exception in user code:")
print("-"*60)
traceback.print_exc(file=sys.stdout)
print("-"*60)
exit(1)
with open('./settings/modules.py', 'w') as f:
f.write("".join(modules))
if __name__=="__main__":
start()

4
cuchulu/debug.sh Normal file
View file

@ -0,0 +1,4 @@
#!/bin/sh
gunicorn -w1 --reload --bind localhost:8080 index:app

14
cuchulu/examples/app.py Normal file
View file

@ -0,0 +1,14 @@
from cuchulu.libraries.mtemplates import env_theme, PTemplate
from cuchulu.libraries.urls import make_url
from bottle import request
from settings import config
from cuchulu.wsgiapp import app
env=env_theme(__file__)
t=PTemplate(env)
@app.route('/example')
def home():
return "Hello World!!"

9
cuchulu/frontend/app.py Normal file
View file

@ -0,0 +1,9 @@
#!/usr/bin/env python3
from cuchulu.wsgiapp import app
from cuchulu.app import run_app
application=app
if __name__ == "__main__":
run_app(app)

View file

@ -0,0 +1,7 @@
#!/usr/bin/env python3
from cuchulu.create_module import start
start()

View file

@ -0,0 +1,7 @@
#!/usr/bin/env python3
from cuchulu.libraries.check_i18n import start
start()

View file

@ -0,0 +1,7 @@
#!/usr/bin/env python3
from cuchulu.libraries.db.dbadmin import start
start()

View file

@ -0,0 +1,7 @@
#!/usr/bin/env python3
from cuchulu.create_module import regenerate_modules_config
regenerate_modules_config()

0
cuchulu/i18n/__init__.py Normal file
View file

0
cuchulu/i18n/__init__py Normal file
View file

88
cuchulu/i18n/admin.py Normal file
View file

@ -0,0 +1,88 @@
#!/usr/bin/env python3
from cuchulu.libraries.i18n import I18n
I18n.l['en-US']=I18n.l.get('en-US', {})
I18n.l['en-US']['admin']=I18n.l['en-US'].get('admin', {})
I18n.l['en-US']['admin']['without_privileges']='Without privileges'
I18n.l['en-US']['admin']['selected_privileges']='Selected privileges'
I18n.l['en-US']['admin']['administrator']='Administrator'
I18n.l['en-US']['admin']['login']='Login'
I18n.l['en-US']['admin']['remember_login']='Remember login?'
I18n.l['en-US']['admin']['recovery_password']='Recovery password?'
I18n.l['en-US']['admin']['remember_tries']='Remember that only have 3 attempts'
I18n.l['en-US']['admin']['applications']='Applications'
I18n.l['en-US']['admin']['welcome_to_admin_dashboard']='Welcome to Admin dashboard'
I18n.l['en-US']['admin']['from_here_you_can_configure_your_site']='From here you can configure your site'
I18n.l['en-US']['admin']['sign_up']='Sign up'
I18n.l['en-US']['admin']['welcome_to_cuchulu']='Welcome to Admin!!!'
I18n.l['en-US']['admin']['send_email']='Email for recovery your password'
I18n.l['en-US']['admin']['send_password_email']='Your new password'
I18n.l['en-US']['admin']['translation_saved_sucessfully']='Translation saved sucessfully'
I18n.l['en-US']['admin']['modules']='Modules'
I18n.l['en-US']['admin']['change_module_to_translate']='Change module to translate'
I18n.l['en-US']['admin']['saving_translation']='Saving translation'
I18n.l['en-US']['admin']['send']='Send'
I18n.l['es-ES']=I18n.l.get('es-ES', {})
I18n.l['es-ES']['admin']=I18n.l['es-ES'].get('admin', {})
I18n.l['es-ES']['admin']['without_privileges']='Sin privilegios'
I18n.l['es-ES']['admin']['selected_privileges']='Privilegios seleccionados'
I18n.l['es-ES']['admin']['administrator']='Administrador'
I18n.l['es-ES']['admin']['login']='Login'
I18n.l['es-ES']['admin']['remember_login']='¿Recordar login?'
I18n.l['es-ES']['admin']['recovery_password']='¿Recuperar password?'
I18n.l['es-ES']['admin']['remember_tries']='Recuerda que sólo tienes 3 intentos'
I18n.l['es-ES']['admin']['applications']='Aplicaciones'
I18n.l['es-ES']['admin']['welcome_to_admin_dashboard']='Bienvenido al panel de administrador'
I18n.l['es-ES']['admin']['from_here_you_can_configure_your_site']='Desde aquí puedes configurar tu site'
I18n.l['es-ES']['admin']['sign_up']='Registrarse'
I18n.l['es-ES']['admin']['welcome_to_cuchulu']='Bienvenido a Administración'
I18n.l['es-ES']['admin']['send_email']='Email para recuperar tu contraseña'
I18n.l['es-ES']['admin']['send_password_email']='Tu nuevo password'
I18n.l['es-ES']['admin']['translation_saved_sucessfully']='Translation saved sucessfully'
I18n.l['es-ES']['admin']['modules']='Modulos'
I18n.l['es-ES']['admin']['change_module_to_translate']='Cambiar modulo para traducir'
I18n.l['es-ES']['admin']['saving_translation']='Guardando traducción'
I18n.l['es-ES']['admin']['send']='Enviar'

104
cuchulu/i18n/common.py Normal file
View file

@ -0,0 +1,104 @@
#!/usr/bin/env python3
from cuchulu.libraries.i18n import I18n
I18n.l['en-US']=I18n.l.get('en-US', {})
I18n.l['en-US']['common']=I18n.l['en-US'].get('common', {})
I18n.l['en-US']['common']['edit']='Edit'
I18n.l['en-US']['common']['delete']='Delete'
I18n.l['en-US']['common']['error_login']='Error, wrong username or password'
I18n.l['en-US']['common']['login']='Login'
I18n.l['en-US']['common']['recovery_password']='Recovery password'
I18n.l['en-US']['common']['sign_up']='Sign up'
I18n.l['en-US']['common']['password_no_match']='Passwords doesn\'t match'
I18n.l['en-US']['common']['search']='Search'
I18n.l['en-US']['common']['pages']='Pages'
I18n.l['en-US']['common']['delete_item_you_sure']='Are you sure for delete this item?'
I18n.l['en-US']['common']['add_item']='Add new item'
I18n.l['en-US']['common']['options']='Options'
I18n.l['en-US']['common']['repeat_password']='Repeat Password'
I18n.l['en-US']['common']['yes']='Yes'
I18n.l['en-US']['common']['no']='No'
I18n.l['en-US']['common']['error_passwords_no_match']='Error: passwords doesn\'t match'
I18n.l['en-US']['common']['error_username_exists']='Error: username already exists'
I18n.l['en-US']['common']['error_email_exists']='Error: this email is already being used'
I18n.l['en-US']['common']['last']='Last'
I18n.l['en-US']['common']['home']='Home'
I18n.l['en-US']['common']['add_new_item']='Add new item'
I18n.l['en-US']['common']['edit_new_item']='Edit item'
I18n.l['en-US']['common']['task_successful']='Task successful'
I18n.l['es-ES']=I18n.l.get('es-ES', {})
I18n.l['es-ES']['common']=I18n.l['es-ES'].get('common', {})
I18n.l['es-ES']['common']['edit']='Edit'
I18n.l['es-ES']['common']['delete']='Delete'
I18n.l['es-ES']['common']['error_login']='Error, wrong username or password'
I18n.l['es-ES']['common']['login']='Login'
I18n.l['es-ES']['common']['recovery_password']='Recovery password'
I18n.l['es-ES']['common']['sign_up']='Sign up'
I18n.l['es-ES']['common']['password_no_match']='Passwords doesn\'t match'
I18n.l['es-ES']['common']['search']='Search'
I18n.l['es-ES']['common']['pages']='Pages'
I18n.l['es-ES']['common']['delete_item_you_sure']='Are you sure for delete this item?'
I18n.l['es-ES']['common']['add_item']='Add new item'
I18n.l['es-ES']['common']['options']='Options'
I18n.l['es-ES']['common']['repeat_password']='Repeat Password'
I18n.l['es-ES']['common']['yes']='Yes'
I18n.l['es-ES']['common']['no']='No'
I18n.l['es-ES']['common']['error_passwords_no_match']='Error: passwords doesn\'t match'
I18n.l['es-ES']['common']['error_username_exists']='Error: username already exists'
I18n.l['es-ES']['common']['error_email_exists']='Error: this email is already being used'
I18n.l['es-ES']['common']['last']='Last'
I18n.l['es-ES']['common']['home']='Home'
I18n.l['es-ES']['common']['add_new_item']='Add new item'
I18n.l['es-ES']['common']['edit_new_item']='Edit item'
I18n.l['es-ES']['common']['task_successful']='Task successful'

View file

View file

@ -0,0 +1,241 @@
#!/usr/bin/env python3
from collections import OrderedDict
from cuchulu.libraries.sessionplugin import get_session
from cuchulu.libraries.urls import make_url
from cuchulu.libraries.i18n import I18n
from cuchulu.libraries.httputils import GetPostFiles
from cuchulu.libraries.keyutils import create_key_encrypt, create_key_encrypt_256, create_key
from cuchulu.libraries.db.formsutils import generate_csrf
from bottle import response,request
from cuchulu.libraries.db.webmodel import WebModel
from time import time
try:
from settings import config
except:
class config:
admin_folder='admin'
try:
from settings import config_admin
except:
class config_admin:
modules_admin=[]
#Function for get an admin url
def make_admin_url(url, query_args={}):
"""Function for get an admin url
A special function based in make_url for get admin urls. You can use only the module admin part in the url and get a real url for use in your templates or other functions.
Args:
url (str): The url without admin part for use how base. Example: with 'pages' as url value you get http://localhost:8080/admin/pages
query_args (dict): A serie of dictionary values where you get a url query result as it: {'key1': 'value1', 'key2': 'value2'} -> key1=value1&key2=value2
Returns:
str: A new url valid for use in href links directing to admin site
"""
return make_url('%s/%s' % (config.admin_folder, url), query_args)
def get_language(s):
"""Function for get language from a session
With this function you gan get easily the language of session
Args:
s (session): A session object where the language value is stored
Returns:
str: The language string
"""
s['lang']=s.get('lang', None)
lang_selected=None
if s['lang']!=None:
lang_selected=s['lang']
else:
s['lang']=I18n.default_lang
s.save()
lang_selected=I18n.default_lang
return lang_selected
def get_menu(modules_admin):
"""Function for get a ordered dict with modules admin
With this method you get a menu ordered dict for use internally in admin module.
Args:
modules_admin (OrderedDict): The ordereddict used get it from admin configuration of Cuchulu system
Returns:
OrderedDict: A new dict prepared for use in admin module.
"""
menu=OrderedDict()
icon=OrderedDict()
for mod in modules_admin:
if type(mod[1]).__name__!='list':
menu[mod[2]]=mod
if len(menu[mod[2]])<4:
menu[mod[2]].append('<i class="fa fa-circle-o" aria-hidden="true"></i>')
else:
menu[mod[2]][3]='<i class="fa {}" aria-hidden="true"></i>'.format(menu[mod[2]][3])
else:
menu[mod[2]]=mod[0]
if len(mod)<4:
menu[mod[2]]='<i class="fa fa-arrow-down" aria-hidden="true"></i>'+menu[mod[2]]
for submod in mod[1]:
if submod[2] in menu:
print('WARNING: you would not set the admin url for '+submod[2]+' with same general name of module if is not stand alone admin file')
menu[submod[2]]=submod
if len(menu[submod[2]])<4:
menu[submod[2]].append('<i class="fa fa-circle-o" aria-hidden="true"></i>')
else:
menu[submod[2]][3]='<i class="fa {}" aria-hidden="true"></i>'.format(menu[submod[2]][3])
return menu
def check_login():
"""Function for check if correct login in admin module
With this function you can check if the online user is login or not
"""
s=get_session()
if 'login' in s:
if 'privileges' in s:
if s['privileges']==2:
return True
return False
def login_model(ModelLogin, session='', enable_tries=False):
""" Function for standard login
"""
connection=WebModel.connection()
user_admin=ModelLogin(connection)
getpostfiles=GetPostFiles()
getpostfiles.obtain_post()
getpostfiles.post['username']=getpostfiles.post.get('username', '')
getpostfiles.post['password']=getpostfiles.post.get('password', '')
username=user_admin.fields['username'].check(getpostfiles.post['username'])
password=getpostfiles.post['password'].strip()
user_admin.conditions=['WHERE username=%s', [username]]
arr_user=user_admin.select_a_row_where(['id', 'username', 'password', 'privileges', 'lang', 'num_tries', 'email', 'theme'])
if arr_user==False:
connection.close()
return {'error': 1, 'csrf_token': generate_csrf()}
else:
num_tries=int(arr_user['num_tries'])
if arr_user['num_tries']<3:
if user_admin.fields['password'].verify(password, arr_user['password']):
s=get_session()
s[session+'id']=arr_user['id']
s[session+'login']=1
s[session+'privileges']=arr_user['privileges']
s[session+'lang']=arr_user['lang']
s[session+'email']=arr_user['email']
s[session+'username']=arr_user['username']
s[session+'theme']=str(arr_user['theme'])
if s['lang']=='':
s['lang']=I18n.default_lang
remember_login=getpostfiles.post.get(session+'remember_login', '0')
if remember_login=='1':
timestamp=time()+315360000
random_text=create_key_encrypt()
#Update user with autologin token
user_admin.check_user=False
user_admin.conditions=['WHERE username=%s', [username]]
user_admin.valid_fields=['token_login']
user_admin.reset_require()
if user_admin.update({'token_login': random_text}):
response.set_cookie(session+'remember_login', random_text, path=config.session_opts['session.path'], expires=timestamp, secret=key_encrypt)
#else:
#print(user_admin.query_error)
s.save()
connection.close()
return {'error': 0}
else:
user_admin.check_user=False
user_admin.conditions=['WHERE username=%s', [username]]
user_admin.valid_fields=['num_tries']
user_admin.reset_require()
if enable_tries:
user_admin.update({'num_tries': arr_user['num_tries']+1})
connection.close()
return {'error': 1, 'csrf_token': generate_csrf()}
else:
connection.close()
return {'error': 1, 'csrf_token': generate_csrf()}

View file

@ -0,0 +1,70 @@
#!/usr/bin/env python3
from cuchulu.libraries.mtemplates import PTemplate
from cuchulu.libraries.adminutils import check_login, get_language, get_menu
from cuchulu.libraries.db.webmodel import WebModel
from cuchulu.libraries.sessions import get_session
from cuchulu.libraries.i18n import I18n
try:
from settings import config
except:
class config:
admin_folder='admin'
try:
from settings import config_admin
except:
class config_admin:
modules_admin=[]
#Load menu in runtime
menu=get_menu(config_admin.modules_admin)
def base_admin(func_view, env, title, **args):
"""Simple function for make admin sites using template
Args:
func_view (function): Function that return html code for insert into admin/content.phtml
Returns:
str: HTML code.
"""
env.directories.insert(1, config.cuchulu_root+'/modules/admin/templates')
content_index=''
connection=WebModel.connection()
#Fix, make local variable
t=PTemplate(env)
s=get_session()
if check_login():
lang_selected=get_language(s)
content_index=func_view(connection, t, s, **args)
return t.render_template('admin/content.phtml', title=title, content_index=content_index, menu=menu, lang_selected=lang_selected, arr_i18n=I18n.dict_i18n)
else:
redirect(make_url(config.admin_folder))
def base_simple_admin(func_view, env, title, **args):
if check_login():
return func_view(connection, t, s, **args)

View file

@ -0,0 +1,205 @@
#!/usr/bin/env python3
import argparse
import os
import re
from pathlib import Path
from importlib import import_module
from cuchulu.libraries.i18n import I18n
from settings import config
pattern=re.compile(r'^\w+\.(py|html|phtml|js)$')
ignored=re.compile(r'^[__|\.].*$')
lang_p=re.compile(r"I18n\.lang\('(.*?)',\s+'(.*?)',\s+'(.*?)'\)")
lang_t=re.compile(r"\${lang\('(.*?)',\s+'(.*?)',\s+'(.*?)'\)\}")
tmp_lang={}
def start():
global lang_p
global lang_t
# Module to search a file where save the file.
parser = argparse.ArgumentParser(description='A tool for create python language files')
parser.add_argument('--module', help='The module where search lang files', required=False)
args = parser.parse_args()
#Without arguments, search in cuchulu directory all language files
path_save='cuchulu/i18n'
path='cuchulu'
if args.module!=None:
path=args.module
path_save=args.module+'/i18n'
if args.module.endswith('/'):
args.module=args.module[:-1]
module_base=os.path.basename(args.module)
lang_p=re.compile(r"I18n\.lang\('({}?)',\s+'(.*?)',\s+'(.*?)'\)".format(module_base))
#lang_t=re.compile("\${lang\('("+module_base+"?)',\s+'(.*?)',\s+'(.*?)'\)\}")
lang_t=re.compile(r"lang\('({}?)',\s+'(.*?)',\s+'(.*?)'\)".format(module_base))
lang_s=re.compile(r"slang\('(.*?)',\s+'(.*?)'\)")
if not os.path.isdir(path):
print("Error: directory to scan doesn't exists")
exit(1)
scandir(path, path_save)
#Save the files
file_lang=''
for module in tmp_lang.keys():
# Save in a file
real_path=path_save
if not os.path.isdir(real_path):
p=Path(real_path)
p.mkdir(0o755, True)
try:
path_module=path_save.replace('/', '.')+'.'+module
import_module(path_module)
#Add values to tmp lang
#for real_key, real_text in I18n.l[lang][module].items():
#tmp_lang[module][real_key]=real_text
except:
pass
i=Path(real_path+'/__init__py')
i.touch(0o644)
file_lang="#!/usr/bin/env python3\n\n"
file_lang+="from cuchulu.libraries.i18n import I18n\n\n"
for lang in I18n.dict_i18n:
#I18n.l['en-US']['admin']=I18n.l['en-US'].get('admin', {})
file_lang+="I18n.l['%s']=I18n.l.get('%s', {})\n\n" % (lang, lang)
file_lang+="I18n.l['"+lang+"']['"+module+"']=I18n.l['"+lang+"'].get('"+module+"', {})\n\n"
I18n.l[lang]=I18n.l.get(lang, {})
I18n.l[lang][module]=I18n.l[lang].get(module, {})
for key, text in tmp_lang[module].items():
if not key in I18n.l[lang][module]:
I18n.l[lang][module][key]=text
file_lang+="I18n.l['"+lang+"']['"+module+"']['"+key+"']='"+I18n.l[lang][module][key].replace("'", "\\'")+"'\n\n"
final_file=real_path+'/'+module+'.py'
f=open(final_file, 'w')
f.write(file_lang)
f.close()
pass
def scandir(path, module_search=''):
list=os.listdir(path)
for name in list:
new_path=path+'/'+name
if os.path.isdir(new_path):
if ignored.match(name)==None:
scandir(new_path)
elif pattern.match(name)!=None and ignored.match(name)==None:
f=open(new_path)
for line in f:
#[('pokermind', 'performance_questions_default', 'Performance questions default'), ('pokermind', 'performance_questions_defasult', 'Performance questions defaufflt')]
match_p=lang_p.findall(line)
match_t=lang_t.findall(line)
if match_p!=None:
for m in match_p:
module=m[0]
symbol=m[1]
text_default=m[2]
tmp_lang[module]=tmp_lang.get(module, {})
tmp_lang[module][symbol]=tmp_lang[module].get(symbol, text_default)
if match_t!=None:
"""
module=match_t.group(1)
symbol=match_t.group(2)
text_default=match_t.group(3)
tmp_lang[module]=tmp_lang.get(module, {})
tmp_lang[module][symbol]=tmp_lang[module].get(symbol, text_default)
"""
for m in match_t:
module=m[0]
symbol=m[1]
text_default=m[2]
tmp_lang[module]=tmp_lang.get(module, {})
tmp_lang[module][symbol]=tmp_lang[module].get(symbol, text_default)
f.close()
#print('archivo->'+path+'/'+name)
# Open file
# obtain modules, keys, and default text
#Open all files in path specified. If not specified, see in all files recursively in path.
#Extract lang and I18n.lang and fill i18n property that save the values of language texts, only extracs key specified in option key, if not specified, extract last member of path key.
# Open all language files in a loop with modules from dictionary created from open files, if module path is not specified, the file is in cuchulu.i18n. With module path the language files are saved in i18n directory into the path, for example if path is modules/panel, the files are saved in modules/panel/i18n/example.py. If key option is saved then only saved lang with keys selected. Normally you only need a file by module and by default. key option is the last member of path. For example, you can create a language file for a module and use in other module, but don't extract key used in the other module language file used.
# THe array i18n is overwrited loading the lang files.
# Save the files in specified path.
if __name__=='__main__':
start()

View file

@ -0,0 +1,782 @@
import time
from datetime import date, datetime, tzinfo
import arrow
# from babel.dates import format_date, format_datetime, format_time, get_timezone, UTC
try:
from settings import config
except:
config={}
#from cuchulu.libraries.sessions import get_session
from os import environ
"""Simple hook for timedate functions from Arrow datetime module. Maybe in the future use native python datetime functions or other libraries. Is simply an abstraction for not depend of particular library.
"""
sql_format_time='YYYYMMDDHHmmss'
"""str: variable for define basic string for format dates
By default, datetime module use YYYYMMDDHHmmss string for define dates and time. Tipically is used for sql operations in cuchulu2 framework.
"""
format_date_txt="YYYY/MM/DD"
"""str: variable for define basic formatted date string
"""
format_time_txt="HH:mm:ss"
"""str: variable for define basic formatted time string
"""
timezone='Europe/Madrid'
"""str: basic timezone for dates, by default, Europe/Madrid
"""
"""If default are changed in settings/config, change variables
"""
if hasattr(config, 'format_date'):
format_date_txt=config.format_date
if hasattr(config, 'format_time'):
format_time_txt=config.format_time
if hasattr(config, 'timezone'):
timezone=config.timezone
def set_timezone():
"""Simple function for change the timezone in general environment of python
"""
environ['TZ']=environ.get('TZ', timezone)
if environ['TZ']!=timezone:
environ['TZ']=timezone
time.tzset()
"""
def set_timezone_session():
s=get_session()
timezone_local=timezone
if s!=None:
if 'timezone' in s:
timezone_local=s['timezone']
#timezone_local=s.get('timezone', timezone)
environ['TZ']=environ.get('TZ', timezone_local)
if environ['TZ']!=timezone_local:
environ['TZ']=timezone_local
time.tzset()
#request.environ['TIMEZONE'] = request.environ['PATH_INFO'].rstrip('/')
"""
def format_timedata(time):
"""Function for get separated year, month, day, hour, minute and second from sql_format_time string
Args:
time (str): A YYYYMMDDHHmmss string for get datetime components from there.
Returns:
list: A dict with datetime components (year, month, day, hour, minute, second).
"""
year=0
month=0
day=0
hour=0
minute=0
second=0
ampm=''
try:
year=int(time[:4])
month=int(time[4:6])
day=int(time[6:8])
hour=int(time[8:10])
minute=int(time[10:12])
second=int(time[12:14])
ampm=int(time[14:16])
except:
pass
if ampm=='PM' or ampm=='pm':
if hour>0:
hour+=12
return (year, month, day, hour, minute, second)
def checkdatetime(y, m, d, h, mi, s):
"""Check if a series of datetime separated elements are correct, the datetime values are type int
Args:
y (int): Year of datetime
m (int): month
d (int): day
h (int): hour
mi (int): minute
s (int): seconds
Returns:
bool: If values are correct, return True, otherwise return False
"""
try:
#test=datetime.strptime(str(y)+'-'+str(m)+'-'+str(d)+' '+str(h)+'-'+str(mi)+'-'+str(s), '%Y-%m-%d %H-%M-%S')
test=arrow.arrow.Arrow(y, m, d, h, mi, s)
return True
except:
return False
# Get the localtime
def now(utc=False, tz=''):
"""Returns the actual datetime in YYYYMMDDHHmmss format.
Args:
utc (bool): If True, the datetime is returned in UTC timezone
tz (str, optional): Timezone name, example: Europe/Madrid. If set the datetime is returned in the timezone selected
Returns:
str: Return actual datetime
"""
if not utc:
if tz=='':
actual=arrow.now().format(sql_format_time)
else:
#actual=arrow.to(tz).now().format(sql_format_time)
utc=arrow.utcnow()
actual=utc.to(tz).format(sql_format_time)
else:
actual=arrow.utcnow().format(sql_format_time)
return actual
def today(utc=False,tz=''):
"""Returns the actual date in YYYYMMDDHHmmss format.
Is different from (now) function because return the date to 00:00:00 time
Args:
utc (bool): If True, the date is returned in UTC timezone
tz (str, optional): Timezone name, example: Europe/Madrid. If set the date is returned in the timezone selected
Returns:
str: Return actual date with 00:00:00 how time
"""
return now(utc, tz)[:8]+'000000'
# Get actual timestamp
def obtain_timestamp(timeform):
"""Get the timestamp from datetime in YYYYMMDDHHmmss format.
Args:
timeform (str): Datetime in YYYYMMDDHHmmss format.
Returns:
int: datetime in timestamp format
"""
y, m, d, h, mi, s=format_timedata(timeform)
if checkdatetime(y, m, d, h, mi, s):
#timestamp=int(time.mktime((y, m, d, h, mi, s, 0, 0, -1)))
timestamp=arrow.arrow.Arrow(y, m, d, h, mi, s).timestamp()
return timestamp
#return mktime($h, $mi, $s, $m, $d, $y);
else:
return False
# timestamp is gmt time, convert in normal time
def timestamp_to_datetime(timestamp, sql_format_time=sql_format_time):
"""Turn datetime in YYYYMMDDHHmmss format.
Args:
timestamp (int): The timestamp for convert
Returns:
str: Datetime in YYYYMMDDHHmmss format
"""
return arrow.get(timestamp).format(sql_format_time)
# Get a utc timestamp and convert to local
def timestamp_to_datetime_local(timestamp, tz='', sql_format_time=sql_format_time):
"""Get a utc timestamp and convert to timezone datetime in YYYYMMDDHHmmss format.
Args:
timestamp (int): The timestamp for convert in datetime
tz (str, optional): If you want convert to other timezone, set it.
Returns:
str: Datetime in YYYYMMDDHHmmss format in selected timezone datetime
"""
t=arrow.get(timestamp)
if tz=='':
tz=environ['TZ']
return t.to(tz).format(sql_format_time)
def format_datetime(format_time, timeform, func_utc_return):
"""Get a datetime in YYYYMMDDHHmmss format and convert in other str datetime (normally, same YYYYMMDDHHmmss format). Is a primitive function for other high level datetime functions.
Args:
format_time (str): The strtime string used for format the datetime
timeform (str): datetime in YYYYMMDDHHmmss format to convert to new format
func_utc_return (function): A function used for get the datetime.
Returns:
If timestamp is False, return False, if timestamp is valid, return the datetime formatted
"""
timestamp=obtain_timestamp(timeform)
if timestamp:
t=func_utc_return(timestamp)
return t.format(format_time)
else:
return False
# This method parse local time to gmt
def local_to_gmt(timeform, sql_format_time=sql_format_time):
"""Get a datetime in YYYYMMDDHHmmss format and convert in other str datetime. Is a primitive function for other high level datetime functions.
Expects that timeform was in time not gmt and convert to gmt
Args:
timeform (str): datetime in YYYYMMDDHHmmss format to convert to new format
sql_format_time (str, optional): by default, the format is YYYYMMDDHHmmss, you can put other formatted str formats for date, here.
Returns:
If timeform is False, return False, if timeform is valid, return the datetime formatted
"""
return format_datetime(sql_format_time, timeform, substract_utc)
# time.localtime is useless, you need sum the time offset to the date
def gmt_to_local(timeform, sql_format_time=sql_format_time):
"""Get a datetime in YYYYMMDDHHmmss format in UTC and convert in other str datetime. Is a primitive function for other high level datetime functions.
Expects that timeform was in time gmt and convert to localtime
Args:
timeform (str): datetime in YYYYMMDDHHmmss format to convert to new format
sql_format_time (str, optional): by default, the format is YYYYMMDDHHmmss, you can put other formatted str formats for date, here.
Returns:
If timeform is False, return False, if timeform is valid, return the datetime formatted
"""
return format_datetime(sql_format_time, timeform, sum_utc)
def format_time(timeform):
"""Get a datetime in YYYYMMDDHHmmss format and convert in HH:mm:ss UTC format. Is a primitive function for other high level datetime functions.
Args:
timeform (str): datetime in YYYYMMDDHHmmss format to convert to new format
Returns:
If timeform is False, return False, if timeform is valid, return the datetime formatted in UTC
"""
return format_datetime(format_time_txt, timeform, sum_utc)
def format_date(timeform):
"""Get a datetime in YYYYMMDDHHmmss format and convert in YYYY/MM/DD UTC format. Is a primitive function for other high level datetime functions.
Args:
timeform (str): datetime in YYYYMMDDHHmmss format to convert to new format
Returns:
If timeform is False, return False, if timeform is valid, return the datetime formatted in UTC
"""
return format_datetime(format_date_txt, timeform, sum_utc)
def format_fulldate(timeform):
"""Get a datetime in YYYYMMDDHHmmss format and convert in YYYY/MM/DD HH:mm:ss UTC format. Is a primitive function for other high level datetime functions.
Args:
timeform (str): datetime in YYYYMMDDHHmmss format to convert to new format
Returns:
If timeform is False, return False, if timeform is valid, return the datetime formatted in UTC
"""
return format_datetime(format_date_txt+' '+format_time_txt, timeform, sum_utc)
def format_local_time(timeform):
"""Get a datetime in YYYYMMDDHHmmss format and convert in HH:mm:ss format. Is a primitive function for other high level datetime functions.
Args:
timeform (str): datetime in YYYYMMDDHHmmss format to convert to new format
Returns:
If timeform is False, return False, if timeform is valid, return the datetime formatted
"""
return format_datetime(format_time_txt, timeform, no_utc)
def format_local_date(timeform):
"""Get a datetime in YYYYMMDDHHmmss format and convert in YYYY/MM/DD format. Is a primitive function for other high level datetime functions.
Args:
timeform (str): datetime in YYYYMMDDHHmmss format to convert to new format
Returns:
If timeform is False, return False, if timeform is valid, return the datetime formatted
"""
return format_datetime(format_date_txt, timeform, no_utc)
def format_local_fulldate(timeform):
"""Get a datetime in YYYYMMDDHHmmss format and convert in YYYY/MM/DD HH:mm:ss format. Is a primitive function for other high level datetime functions.
Args:
timeform (str): datetime in YYYYMMDDHHmmss format to convert to new format
Returns:
If timeform is False, return False, if timeform is valid, return the datetime formatted
"""
return format_datetime(format_date_txt+' '+format_time_txt, timeform, no_utc)
def format_strtime(strtime, timeform):
"""Get a datetime in YYYYMMDDHHmmss format and convert in strtime string UTC format. Is a primitive function for other high level datetime functions.
Args:
timeform (str): datetime in YYYYMMDDHHmmss format to convert to new format
Returns:
If timeform is False, return False, if timeform is valid, return the datetime formatted in UTC
"""
return format_datetime(strtime, timeform, sum_utc)
def format_local_strtime(strtime, timeform):
"""Get a datetime in YYYYMMDDHHmmss format and convert in strtime string format. Is a primitive function for other high level datetime functions.
Args:
timeform (str): datetime in YYYYMMDDHHmmss format to convert to new format
Returns:
If timeform is False, return False, if timeform is valid, return the datetime formatted
"""
return format_datetime(strtime, timeform, no_utc)
#Input is utc timestamp, return local arrow object
def sum_utc(timestamp, tz=''):
"""Get timestamp in UTC and convert in arrow date object with timezone datetime
Args:
timestamp (int): The timestamp for convert in other timezone
tz (str): Timezone of timestamp
Returns:
Return arrow object with new timezone selected
"""
#offset=time.altzone
#return time.localtime(timestamp-offset)
t=arrow.get(timestamp)
if tz=='':
tz=environ['TZ']
return t.to(tz)
#Input is local timestamp, return utc arrow object
def substract_utc(timestamp, tz=''):
"""Get local timestamp and convert in arrow date object with UTC datetime
Args:
timestamp (int): The timestamp for convert in UTC timezone
tz (str): Timezone of timestamp
Returns:
Return arrow object with UTC timezone selected
"""
#offset=time.altzone
#return time.localtime(timestamp+offset)
#t=arrow.get(timestamp).to('UTC')
timeform=timestamp_to_datetime(timestamp)
y, m, d, h, mi, s=format_timedata(timeform)
if tz=='':
tz=environ['TZ']
t=arrow.get(datetime(y, m, d, h, mi, s), tz).to('UTC')
return t
def no_utc(timestamp):
"""Return an arrow object based in timestamp value
Args:
timestamp (int): The timestamp for convert in UTC timezone
Returns:
Return arrow object based in timestamp value
"""
return arrow.get(timestamp)
class TimeClass:
"""Simple abstraction of arrow class, in future i can change arrow class by others
Args:
timestamp (int, str, optional): You can set the initial arrow object with timestamp date or YYYYMMDDHHmmss date format
tz (str): Timezone
Attributes:
utc (bool): If True, the default timezone is UTC, if False, timezone is system default
format_time (str): The default datetime format, YYYYMMDDHHmmss
format_time_txt (str): Time text format, usually HH:mm:ss
format_date_txt (str): Date text format, usually YYYY/MM/DD
format_date_full (str): Full DateTime text format, usually YYYY/MM/DD HH:mm:ss
tz (str): Default timezone for arrow object
"""
def __init__(self, timestamp=None, tz=''):
self.utc=False
self.format_time=sql_format_time
self.format_time_txt=format_time_txt
self.format_date_txt=format_date_txt
self.format_date_full=format_date_txt+' '+format_time_txt
self.tz=environ.get('TZ', 'utc')
if tz:
self.tz=tz
if type(timestamp).__name__=='int':
self.datetime=timestamp_to_datetime(timestamp)
else:
if not timestamp:
self.datetime=now(self.utc, tz)
else:
self.datetime=timestamp
y, m, d, h, mi, s=format_timedata(self.datetime)
self.t=arrow.get(datetime(y, m, d, h, mi, s), self.tz)
def add_month(self, num_months):
"""Method for add months to datetime
Args:
num_months (int): Number of months to add
Returns:
New added datetime
"""
m=self.t.shift(months=+num_months)
return m.format(self.format_time)
def substract_month(self, num_months):
"""Method for substract months to datetime
Args:
num_months (int): Number of months to substract
Returns:
New substracted datetime
"""
m=self.t.shift(months=-num_months)
return m.format(self.format_time)
def add_day(self, num_days):
"""Method for add days to datetime
Args:
num_days (int): Number of days to add
Returns:
New added datetime
"""
m=self.t.shift(days=+num_days)
return m.format(self.format_time)
def substract_day(self, num_days):
"""Method for substract days to datetime
Args:
num_days (int): Number of days to substract
Returns:
New substracted datetime
"""
m=self.t.shift(days=-num_days)
return m.format(self.format_time)
def add_year(self, num_years):
"""Method for add years to datetime
Args:
num_years (int): Number of years to add
Returns:
New added datetime
"""
m=self.t.shift(years=+num_years)
return m.format(self.format_time)
def substract_year(self, num_years):
"""Method for substract years to datetime
Args:
num_years (int): Number of years to substract
Returns:
New substracted datetime
"""
m=self.t.shift(years=-num_years)
return m.format(self.format_time)
def add_hour(self, num_hours):
"""Method for add hours to datetime
Args:
num_hours (int): Number of hours to add
Returns:
New added datetime
"""
m=self.t.shift(hours=+num_hours)
return m.format(self.format_time)
def substract_hour(self, num_hours):
"""Method for substract hours to datetime
Args:
num_hours (int): Number of hours to substract
Returns:
New substracted datetime
"""
m=self.t.shift(hours=-num_hours)
return m.format(self.format_time)
def format(self):
"""Method for get datetime formatted using format_date_full attribute
Returns:
Datetime formatted with format_date_full attribute
"""
return self.t.format(self.format_date_full)
def local_to_utc(self):
"""Method for convert datetime from actual timezone to UTC"""
self.t=self.t.to('utc')
# Only use
def utc_to_local(self):
"""Method for convert datetime from actual timezone from UTC to actual timezone"""
self.t=self.t.to(self.tz)
def local_to_tz(self, tz):
"""Method for convert actual timezone to other timezone"""
self.t=self.t.to(tz)
def now(self, utc=False):
"""Method for get actual datetime.
Args:
utc (bool): If True, then get actual datetime in UTC datetime, if False, get actual datetime in selected timezone in tz attribute
Returns:
Actual datetime formatted in YYYYMMDDHHmmss format.
"""
if not utc:
actual=arrow.now(self.tz).format(sql_format_time)
else:
actual=arrow.utcnow().format(sql_format_time)
return actual
def today(self, utc=False):
"""Method for get today datetime. Get now datetime with 00:00:00 time.
Args:
utc (bool): If True, then get actual datetime in UTC datetime, if False, get actual datetime in selected timezone in tz attribute
Returns:
Actual datetime formatted in YYYYMMDD000000 format.
"""
if utc:
return arrow.utcnow()[:8]+'000000'
else:
return arrow.now(self.tz)[:8]+'000000'
def timestamp_to_datetime(self, timestamp):
"""Method for convert a timestamp in YYYYMMDDHHmmss format.
Args:
timestamp (int): datetime in timestamp format.
Returns:
Datetime in YYYYMMDDHHmmss format.
"""
return arrow.get(timestamp).format(sql_format_time)
def obtain_timestamp(self, timeform):
"""Method for get timestamp from a datetime in YYYYMMDDHHmmss format.
Args:
timeform (str): Datetime in YYYYMMDDHHmmss format.
Returns:
Datetime in YYYYMMDDHHmmss format.If timeform is incorrect, return False
"""
y, m, d, h, mi, s=format_timedata(timeform)
if checkdatetime(y, m, d, h, mi, s):
timestamp=arrow.arrow.Arrow(y, m, d, h, mi, s).timestamp
return timestamp
else:
return False
def format_strtime(self, strtime, timeform):
"""Method for get datetime formatted in strtime format
Args:
strtime (str): The string used for format the datetime
timeform (str): Datetime in YYYYMMDDHHmmss format.
Returns:
Datetime in strtime format.If timeform is incorrect, return False
"""
try:
y, m, d, h, mi, s=format_timedata(timeform)
return arrow.get(datetime(y, m, d, h, mi, s), self.tz).format(strtime)
except:
return False

4
cuchulu/libraries/db/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
*~
*.pyc
__pycache__

View file

@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View file

@ -0,0 +1 @@
# A very simple ORM for Python 3

View file

View file

@ -0,0 +1,435 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.webmodel import PhangoField
from cuchulu.libraries.db import coreforms
from cuchulu.libraries.i18n import I18n
#from bs4 import BeautifulSoup
import bleach
class IntegerField(PhangoField):
"""Class that figure an integer sql type field.
"""
def __init__(self, name, size=11, required=False):
"""
Args:
name (str): The name of field
size (int): The size of the new field in database. By default 11.
required (bool): Boolean for define if field is required or not
"""
super(IntegerField, self).__init__(name, size, required)
self.default_value=0
self.type_sql='int({})'.format(self.size)
self.default_value=0
self.jtype='integer'
self.jformat='int64'
self.jexample='1'
def check(self, value):
"""Method for check if value is integer
Args:
value (int): The value to check
"""
self.error=False
self.txt_error=''
try:
value=str(int(value))
if value=="0" and self.required==True:
self.txt_error="The value is zero"
self.error=True
except:
value="0"
self.txt_error="The value is zero"
self.error=True
return value
def get_type_sql(self):
"""Method for return the sql code for this type
"""
return 'INT('+str(self.size)+') NOT NULL DEFAULT "0"'
class BigIntegerField(IntegerField):
"""Class that figure an big integer sql type field.
Only change the sql type with respect to IntegerField
"""
def __init__(self, name, size=11, required=False):
super().__init__(name, size, required)
self.type_sql='bigint({})'.format(self.size)
def get_type_sql(self):
"""Method for return the sql code for this type
"""
return 'BIGINT('+str(self.size)+') NOT NULL DEFAULT "0"'
class FloatField(PhangoField):
"""Class that figure an float sql type field.
Args:
name (str): The name of new field
size (int): The size of the new field in database. By default 11.
required (bool): Boolean for define if
"""
def __init__(self, name, size=11, required=False):
super(FloatField, self).__init__(name, size, required)
self.error_default="The value is zero"
self.default_value=0
self.type_sql='float'.format(self.size)
self.jtype='number'
self.jformat='float'
def check(self, value):
"""Method for check if value is integer
Args:
value (float): The value to check
"""
self.error=False
self.txt_error=''
try:
value=str(value)
if value.find(',')!=-1:
value=value.replace(',', '.')
value=str(float(value))
if value==0 and self.required==True:
self.txt_error=self.error_default
self.error=True
except:
value="0"
self.txt_error=self.error_default
self.error=True
return value
def get_type_sql(self):
return 'FLOAT NOT NULL DEFAULT "0"'
class DecimalField(FloatField):
"""PhangoField field for Decimals fields."""
def __init__(self, name, size=11, required=False):
super().__init__(name, size, required)
self.type_sql='decimal(20,2)'
self.jtype='number'
def get_type_sql(self):
return 'DECIMAL(20, 2) NOT NULL DEFAULT "0"'
class DoubleField(FloatField):
"""PhangoField field for Double fields."""
def __init__(self, name, size=11, required=False):
super().__init__(name, size, required)
self.type_sql='double'
self.jtype='number'
self.jformat='double'
def get_type_sql(self):
return 'DOUBLE NOT NULL DEFAULT "0"'
class CharField(PhangoField):
"""Simple alias for PhangoField"""
pass
class TextField(PhangoField):
"""Class used for text fields
Class used for text fields, use TEXT sql type for the this field.
"""
def __init__(self, name, required=False):
"""Init TextField class different to standard PhangoField
Args:
name (str): The name of new field
required (bool): Boolean for define if field is required or not
Attributes:
set_default (str): Set if the value es NOT NULL or not
"""
super().__init__(name, 11, required)
self.type_sql='text'
self.set_default='NOT NULL'
def get_type_sql(self):
"""Method for return the sql code for this type
"""
return 'TEXT '+self.set_default
class LongTextField(TextField):
"""Class used for long text fields (32 bits size, 4G)
Class used for text fields, use LONGTEXT sql type for the this field.
"""
def __init__(self, name, required=False):
"""Init TextField class different to standard PhangoField
Args:
name (str): The name of new field
required (bool): Boolean for define if field is required or not
Attributes:
set_default (str): Set if the value es NOT NULL or not
"""
super().__init__(name, required)
self.type_sql='longtext'
def get_type_sql(self):
"""Method for return the sql code for this type
"""
return 'LONGTEXT '+self.set_default
class HTMLField(TextField):
"""Class used for html fields
Class used for html fields, use TEXT sql type for the this field because is children of TextField. In this method self.escape is used for convert " to &quot;
"""
def __init__(self, name, required=False):
"""Init HTMLField class different to standard PhangoField
Args:
name (str): The name of new field
required (bool): Boolean for define if field is required or not
Attributes:
trusted_tags (list): A list with safe tags.
"""
super().__init__(name, required)
self.trusted_tags=['b', 'strong']
def check(self, value):
"""Check method for html values
This check method use beautifulsoap for clean and format html code
"""
# leach.clean('<p>"trial"</p><script></script>', tags=('p'))
"""
soup=BeautifulSoup(value, features='html.parser')
for tag in soup.findAll(True):
if tag.name not in self.trusted_tags:
tag.hidden=True
value=soup.renderContents().decode('utf-8')
if self.escape:
return value.replace('"', '&quot;')
else:
return value
"""
value=bleach.clean(value, tags=self.trusted_tags)
if self.escape:
return value.replace('"', '&quot;')
else:
return value
class ForeignKeyField(IntegerField):
"""Subclass of IntegerField for create Foreign keys
A subclass of IntegerField used for create foreign keys in related tables.
"""
def __init__(self, name, related_table, size=11, required=False, identifier_field='id', named_field="id", select_fields=[]):
"""
Args:
name (str): Name of field
related_table (WebModel): The table-model related with this foreign key
size (int): The size of the new field in database. By default 11.
required (bool): Boolean for define if field is required or not
identifier_field (str): The Id field name from related table
named_field (str): The field from related table used for identify the row seleted from related table
select_fields (list): A series of fields names from related
"""
super(ForeignKeyField, self).__init__(name, size, required)
self.table_id=related_table.name_field_id
self.table_name=related_table.name
self.related_model=related_table
self.identifier_field=identifier_field
self.named_field=named_field
self.select_fields=select_fields
self.foreignkey=True
self.change_form(coreforms.SelectModelForm, [related_table, self.named_field, self.identifier_field])
self.default_value=None
def check(self, value):
value=super().check(value)
if value=='0' or value==0:
value=None
return value
def get_type_sql(self):
"""Method for return the sql code for this type
"""
return 'INT NULL'
class BooleanField(IntegerField):
"""Field for boolean values
"""
def __init__(self, name, size=1):
"""
Args:
name (str): Name of field
size (int): The size of the new field in database. By default 11.
"""
required=False
self.yes_text=I18n.lang('common', 'yes', 'Yes')
self.no_text=I18n.lang('common', 'no', 'No')
super(IntegerField, self).__init__(name, size, required)
self.default_error="Need 0 or 1 value"
self.default_value=0
self.type_sql='tinyint(1)'
self.jtype='boolean'
#self.jformat='0'
self.jexample='0'
def check(self, value):
self.error=False
self.txt_error=''
try:
value=int(value)
if value<0 or value>1:
self.txt_error=self.default_error
self.error=True
value=0
except:
self.error=True
self.txt_error=self.default_error
value=0
value=str(value)
return value
def get_type_sql(self):
"""Method for return the sql code for this type
"""
return 'BOOLEAN NOT NULL DEFAULT "0"'
def show_formatted(self, value):
value=int(value)
if value==0:
value=self.no_text
else:
value=self.yes_text
return str(value)

View file

@ -0,0 +1,297 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for Bottle.py, mako and others and construct a simple headless cms.
Copyright (C) 2024 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from collections import OrderedDict
from html import escape
#Forms para python3
class BaseForm:
"""The class used by all forms classes
BaseForm is the base class used for all form classes.
A form class is used for generate simple html forms, how input type, text type, hidden type, etc. PhangoField classes use this forms for generate automatically forms using GenerateAdminClass and others.
"""
def __init__(self, name, value):
"""
Args:
name (str): The html name for this form
value (str): The default value of this html form.
Attributes:
label (str): Label used in functions how show_form that generate a complete html form from a form class list
name (str): Name of the html form.
default_value (mixed): The default value of the form. Equal to value in typical html form.
css (str): Used for add css classes to the html form
type (str): Variable used for conventional html forms with html tag <input>
field (PhangoField): Field related with this form. Used in PhangoField.
required (boolean): If form is required or not, used in functions that generate forms.
name_field_id (str): The html id for the html form. Used for html things.
help (str): A string with help text, used in functions that generate forms.
"""
self.label=name
self.name=name
self.default_value=value
self.css=''
self.type='text'
self.field=None
self.required=False
self.txt_error=''
self.error=False
self.name_field_id=self.name+'_form'
self.help=''
self.placeholder=''
def form(self):
"""Method for returm the html code of the form
"""
return '<input type="'+self.type+'" class="'+self.css+'" name="'+self.name+'" id="'+self.name_field_id+'" value="'+self.setform(self.default_value)+'" placeholder="'+self.placeholder+'" />'
def show_formatted(self, value):
"""Method for show the value of form formatted
Args:
value (mixed): The value of field form
"""
return value
#Method for escape value for html input. DON'T CHANGE IF YOU DON'T KNOWN WHAT ARE YOU DOING
def setform(self, value):
"""A method for set the value in the form for escape and other things
Args:
value (mixed): The value of field form for set
"""
value=str(value)
return value.replace('"', '&quot;').replace("'", '&#39;')
def change_name(self, new_name):
"""A method for change the default form html name of the field form
Args:
new_name (str): The new name of the form. Always is finished with _form suffix
"""
self.name=new_name
self.name_field_id=self.name+'_form'
return ""
class SimpleTextForm(BaseForm):
"""Form for simple text
"""
def __init__(self, name, value):
super().__init__(name, value)
self.after_text=''
def form(self):
return super().form()+' '+self.after_text
class TextForm(BaseForm):
"""Form for simple text form
"""
def __init__(self, name, value):
super(TextForm, self).__init__(name, value)
def form(self):
return '<textarea class="'+self.css+'" name="'+self.name+'" id="'+self.name+'_form">'+self.setform(self.default_value)+'</textarea>'
class PasswordForm(BaseForm):
"""Form for password forms
"""
def __init__(self, name, value, show_password=False):
super(PasswordForm, self).__init__(name, value)
self.type='password'
self.show_password=show_password
def setform(self, value):
if not self.show_password:
return ""
else:
return value
class HiddenForm(BaseForm):
"""Form for hidden forms
"""
def __init__(self, name, value):
super(HiddenForm, self).__init__(name, value)
self.type='hidden'
class SelectForm(BaseForm):
"""Form for select html form
"""
def __init__(self, name, value, elements=OrderedDict()):
"""
Args:
name (str): The html name for this form
value (str): The default value of this html form
elements (OrderedDict): An ordered dict with the keys(the form value) and text label. Example, if you have a OrderedDict how {'0': 'Value selected'} in a html select form you have the next result: <select name="name"><option value="0">Value selected</option></selected>
"""
super(SelectForm, self).__init__(name, value)
self.arr_select=elements
def form(self):
the_form='<select name="'+self.name+'" id="'+self.name_field_id+'">\n'
arr_selected={self.default_value: 'selected'}
for k,v in self.arr_select.items():
arr_selected[k]=arr_selected.get(k, '')
the_form+="<option value=\""+self.setform(str(k))+"\" "+arr_selected[k]+">"+self.setform(str(v))+"</option>"
the_form+='</select>\n'
return the_form
class SelectModelForm(SelectForm):
"""Form for select html using a webmodel how base for get the data
"""
def __init__(self, name, value, model, field_name, field_value, field_parent=None):
"""
Args:
name (str): The html name for this form
value (str): The default value of this html form.
model (WebModel): The webmodel used for get the data for arr_select
field_name (str): The field used for get the name of every option in select
field_value (str): The field used for get the value of every option in select
field_parent (int): If the model have parents or children, the value of this argument
"""
super(SelectModelForm, self).__init__(name, value)
try:
self.default_value=int(self.default_value)
except:
self.default_value=0
self.arr_select=OrderedDict()
self.model=model
self.field_name=field_name
self.field_value=field_value
self.field_parent=field_parent
self.form=self.normal_form
if self.field_parent!=None:
self.form=self.parent_form
def normal_form(self):
"""Method for prepare the form hierated from SelectForm class, without parents
Method for prepare the form hierated from SelectForm class getting data from database using model attribute.
"""
self.arr_select['']=''
with self.model.select([self.field_name, self.field_value], True) as cur:
for arr_value in cur:
#print(self.model.fields[self.field_name])
self.arr_select[arr_value[self.field_value]]=self.model.fields[self.field_name].show_formatted(arr_value[self.field_name])
try:
self.default_value=int(self.default_value)
except:
self.default_value=0
return super().form()
def parent_form(self):
"""Method for prepare the form hierated from SelectForm class, with parents
Method for prepare the form hierated from SelectForm class getting data from database using model attribute.
"""
self.arr_select['']=''
arr_son={}
old_conditions=self.model.conditions
old_limit=self.model.limit
self.model.limit=''
self.model.set_conditions('WHERE 1=1', [])
with self.model.select([self.field_name, self.field_value, self.field_parent], True) as cur:
for arr_value in cur:
if not arr_value[self.field_parent] in arr_son:
arr_son[arr_value[self.field_parent]]=[]
if arr_value[self.field_value]!=self.model.model_id:
arr_son[arr_value[self.field_parent]].append([arr_value[self.field_value], self.model.fields[self.field_name].show_formatted(arr_value[self.field_name])])
self.create_son(0, arr_son)
self.model.conditions=old_conditions
self.model.limit=old_limit
try:
self.default_value=int(self.default_value)
except:
self.default_value=0
return super().form()
def create_son(self, parent_id, arr_son, separator=''):
"""Recursive method for generate parents and children dictionary
"""
if parent_id in arr_son:
for son in arr_son[parent_id]:
self.arr_select[son[0]]=separator+son[1]
son_separator=separator
if son[0] in arr_son:
son_separator+='--'
self.create_son(son[0],arr_son, son_separator)

View file

@ -0,0 +1,117 @@
#!/usr/bin/env python3
import sys
import MySQLdb.cursors
import sqlalchemy.pool as pool
import traceback
class SqlClass:
def __init__(self, connection):
self.max_overflow=-1
self.pool_size=15
self.error_connection=""
# Data of connection
self.connection=connection
# Sql connection
self.conn=None
self.connected=False
self.pool_recycle=3600
self.connect()
def connect(self):
"""
if self.conn==None:
"""
try:
def getconn():
return MySQLdb.connect(self.connection['host'],
user=self.connection['user'],
passwd=self.connection['password'],
db=self.connection['db'],
charset='utf8mb4',
cursorclass=MySQLdb.cursors.DictCursor)
"""
if mypool==None:
mypool=pool.QueuePool(getconn, max_overflow=self.max_overflow, pool_size=self.pool_size, recycle=self.pool_recycle, use_threadlocal=False)
"""
self.conn=getconn() #mypool.connect()
self.conn.ping(True)
"""
while not self.conn.open:
self.conn=SqlClass.mypool.connect()
"""
self.connected=True
except:
e = sys.exc_info()[0]
v = sys.exc_info()[1]
self.error_connection="Error in connection: %s %s" % (e, v)
self.conn.close()
raise NameError(self.error_connection)
#Make def query more simple if not debugging.
def query(self, sql_query, arguments=[], name_connection="default"):
#if fetch_type=="ASSOC":
#fetch_type=MySQLdb.cursors.DictCursor
#with self.conn.cursor(MySQLdb.cursors.DictCursor) as cursor:
cursor=self.conn.cursor(MySQLdb.cursors.DictCursor)
try:
cursor.execute(sql_query, arguments)
self.conn.commit()
return cursor
except:
e = sys.exc_info()[0]
v = sys.exc_info()[1]
if hasattr(cursor, '_last_executed'):
sql_query=cursor._last_executed
#, traceback.format_exc()
self.error_connection="Error in query ||%s||Values: %s" % (sql_query, str(arguments))
self.conn.close()
#return False
raise NameError(self.error_connection)
#Fetcho row return dictionary if is defined in query.
#def fetch(self, cursor):
#return cursor.fetchone()
def __del__(self):
if self.conn:
self.conn.close()
def close(self, name_connection="default"):
if self.conn:
self.conn.close()
self.conn=None
pass

View file

@ -0,0 +1,121 @@
#!/usr/bin/env python3
import sys
import pymysql.cursors
pymysql.install_as_MySQLdb
import sqlalchemy.pool as pool
import traceback
mypool=None
class SqlClass:
def __init__(self, connection):
self.max_overflow=-1
self.pool_size=0
self.error_connection=""
# Data of connection
self.connection=connection
# Sql connection
self.conn=None
self.connected=False
self.pool_recycle=3600
self.connect()
def connect(self):
global mypool
if self.conn==None:
try:
def getconn():
return pymysql.connect(self.connection['host'],
user=self.connection['user'],
passwd=self.connection['password'],
db=self.connection['db'],
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
if mypool==None:
mypool=pool.QueuePool(getconn, max_overflow=self.max_overflow, pool_size=self.pool_size, recycle=self.pool_recycle, use_threadlocal=True)
self.conn=mypool.connect()
self.conn.ping(True)
"""
while not self.conn.open:
self.conn=SqlClass.mypool.connect()
"""
self.connected=True
except:
e = sys.exc_info()[0]
v = sys.exc_info()[1]
self.error_connection="Error in connection: %s %s" % (e, v)
self.conn.close()
raise NameError(self.error_connection)
#Make def query more simple if not debugging.
def query(self, sql_query, arguments=[], name_connection="default"):
#self.connect()
#if fetch_type=="ASSOC":
#fetch_type=MySQLdb.cursors.DictCursor
#with self.conn.cursor(MySQLdb.cursors.DictCursor) as cursor:
cursor=self.conn.cursor(pymysql.cursors.DictCursor)
try:
cursor.execute(sql_query, arguments)
self.conn.commit()
return cursor
except:
e = sys.exc_info()[0]
v = sys.exc_info()[1]
if hasattr(cursor, '_last_executed'):
sql_query=cursor._last_executed
#, traceback.format_exc()
self.error_connection="Error in query ||%s||Values: %s" % (sql_query, str(arguments))
self.conn.close()
#return False
raise NameError(self.error_connection)
#Fetcho row return dictionary if is defined in query.
#def fetch(self, cursor):
#return cursor.fetchone()
def __del__(self):
if self.conn:
self.conn.close()
def close(self, name_connection="default"):
if self.conn:
self.conn.close()
self.conn=None
pass

View file

@ -0,0 +1,253 @@
#!/usr/bin/env python3
import sys
#import pymysql.cursors
#pymysql.install_as_MySQLdb
#import sqlalchemy.pool as pool
from sqlalchemy import create_engine
import traceback
#mypool=None
#engine = create_engine('sqlite:///:memory:', echo=True)
engine=None
class SqlClass:
"""Class used how interface to sqlalchemy for connect to mysql engine
Attributes:
cursors_connect (pymysql.cursors.DictCursor): Cursor dict connection to database
disable_pool (boolean): If True then not exists mysql pool, if False, use sql pool for better connections.
pymsql_install (boolean): If True, pymysql is used how mysqldb classic python module.
pool_size (int): The size of the mysql pool.
"""
cursors_connect=None
disable_pool=False
pymysql_install=False
pool_size=15
def __init__(self, connection):
"""
Args:
connection (dict): A dict with the configurations of SqlClass connection
Attributes:
error_connection (str): A string where errors are saved
connection (dict): A dict with the configurations of SqlClass connection
conn (MySQL Connection): A PyMySQL or Mysqldb connection
connected (bool): Simple bool for check if was connected to mysql
pool_recycle (int): Time limite for recycle the pool by inactivity
"""
#self.max_overflow=-1
self.error_connection=""
# Data of connection
self.connection=connection
# Sql connection
self.conn=None
self.connected=False
self.pool_recycle=3600
self.last_query=''
self.connect()
def connect(self):
"""Method for connect to mysql db using pymysql or mysqldb
"""
global engine
if not SqlClass.disable_pool:
if not engine:
try:
if self.connection['db_type']=='pymysql':
import pymysql.cursors
pymysql.install_as_MySQLdb
SqlClass.pymysql_install=True
SqlClass.cursors_connect=pymysql.cursors.DictCursor
else:
import MySQLdb.cursors
SqlClass.cursors_connect=MySQLdb.cursors.DictCursor
engine=create_engine("mysql+%s://%s:%s@%s/%s?charset=utf8mb4" % (self.connection['db_type'], self.connection['user'], self.connection['password'], self.connection['host'], self.connection['db']), pool_recycle=self.pool_recycle, echo_pool=True, pool_size=self.pool_size, pool_pre_ping=True)
#Postgre
#engine = create_engine("postgresql+psycopg2://scott:tiger@localhost:5432/mydatabase")
except:
e = sys.exc_info()[0]
v = sys.exc_info()[1]
self.error_connection="Error in connection: %s %s" % (e, v)
#self.conn.close()
raise NameError(self.error_connection)
self.conn=engine.raw_connection()
#self.conn.ping(True)
else:
if self.connection['db_type']=='pymysql':
import pymysql.cursors
if not SqlClass.pymysql_install:
pymysql.install_as_MySQLdb
SqlClass.pymysql_install=True
"""
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
database='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
"""
self.conn=pymysql.connect(host=self.connection['host'], user=self.connection['user'], passwd=self.connection['password'], db=self.connection['db'], charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
else:
import MySQLdb.cursors
self.conn=MySQLdb.connect(host=self.connection['host'],
user=self.connection['user'],
passwd=self.connection['password'],
db=self.connection['db'],
charset='utf8mb4',
cursorclass=MySQLdb.cursors.DictCursor)
pass
"""
if self.conn==None:
try:
def getconn():
return pymysql.connect(self.connection['host'],
user=self.connection['user'],
passwd=self.connection['password'],
db=self.connection['db'],
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
if mypool==None:
mypool=pool.QueuePool(getconn, max_overflow=self.max_overflow, pool_size=self.pool_size, recycle=self.pool_recycle, use_threadlocal=True)
self.conn=mypool.connect()
self.conn.ping(True)
self.connected=True
except:
e = sys.exc_info()[0]
v = sys.exc_info()[1]
self.error_connection="Error in connection: %s %s" % (e, v)
self.conn.close()
raise NameError(self.error_connection)
"""
#Make def query more simple if not debugging.
def query(self, sql_query, arguments=[], name_connection="default"):
"""Method for send a sql query to mysql server
Args:
sql_query (str): The sql sentence to execute. For data you should use %s character.
arguments (list): The data used in sql sentence. This data substitute the %s characters.
name_connection (str): The name of dict element with the configuration of connection, without used in this moment.
"""
cursor=self.conn.cursor(SqlClass.cursors_connect)
try:
cursor.execute(sql_query, arguments)
self.conn.commit()
#if hasattr(cursor, '_executed'):
# self.last_query=cursor._executed
return cursor
except:
e = sys.exc_info()[0]
v = sys.exc_info()[1]
#if hasattr(cursor, '_executed'):
# self.last_query=cursor._executed
self.error_connection="Error in query ||%s||Values: %s" % (self.last_query, str(arguments))
self.conn.close()
#return False
raise NameError(self.error_connection)
#self.connect()
#if fetch_type=="ASSOC":
#fetch_type=MySQLdb.cursors.DictCursor
#with self.conn.cursor(MySQLdb.cursors.DictCursor) as cursor:
"""
cursor=self.conn.cursor(pymysql.cursors.DictCursor)
try:
cursor.execute(sql_query, arguments)
self.conn.commit()
return cursor
except:
e = sys.exc_info()[0]
v = sys.exc_info()[1]
if hasattr(cursor, '_last_executed'):
sql_query=cursor._last_executed
#, traceback.format_exc()
self.error_connection="Error in query ||%s||Values: %s" % (sql_query, str(arguments))
#return False
raise NameError(self.error_connection)
"""
#Fetcho row return dictionary if is defined in query.
#def fetch(self, cursor):
#return cursor.fetchone()
def __del__(self):
"""Typical method used when class is deleted from memory. Close the connextion if exists.
"""
if self.conn:
self.conn.close()
def close(self, name_connection="default"):
"""Method used for close the connection if you want close connection and open other.
"""
if self.conn:
self.conn.close()
self.conn=None
pass

View file

@ -0,0 +1,481 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import argparse
import os,traceback
import sys, inspect
import shutil
import re
from datetime import date
from pathlib import Path
from colorama import init, Fore, Back, Style
from importlib import import_module, reload
from cuchulu.libraries.db.webmodel import WebModel
sys.path.insert(0, os.path.realpath('.'))
try:
from settings import config
except:
#print('You need a settings directory with a cuchulu configuration')
#sys.exit(1)
pass
def start():
"""Function for create and update mysql tables using webmodel classes and fields how source.
"""
connection=WebModel.connection()
#connection.connect_to_db(WebModel.connections['default'])
parser = argparse.ArgumentParser(description='A tool for create tables in databases using models from Cromosoma')
parser.add_argument('--model', help='Model python path', required=True)
parser.add_argument('--config', help='The config file', required=False)
args = parser.parse_args()
init()
#Import config
config_file='config'
if args.config!=None:
config_file=args.config
try:
config=import_module('settings.'+config_file)
except:
e = sys.exc_info()[0]
v = sys.exc_info()[1]
print(Fore.WHITE+Back.RED+Style.BRIGHT+"Config file not found: %s %s" % (e, v))
exit(1)
#print(WebModel.connections)
if '/' in args.model:
args.model=args.model.replace('/', '.')[:-3] #.replace('.py', '')
try:
model=import_module(args.model)
for name, obj in inspect.getmembers(sys.modules[model.__name__]):
if inspect.isclass(obj):
if obj.__module__==args.model and hasattr(obj, 'webmodel'):
WebModel.model[name.lower()]=obj(connection)
#WebModel.modelobj
except:
"""
e = sys.exc_info()[0]
v = sys.exc_info()[1]
print(Fore.WHITE+Back.RED+Style.BRIGHT +"Error, file with model not found: %s %s" % (e, v))
"""
print("Exception in user code:")
print("-"*60)
traceback.print_exc(file=sys.stdout)
print("-"*60)
exit(1)
#load the table of databases
cursor=connection.query("show tables")
table_exists=[]
for row in cursor:
table=list(row.values())[0]
if table in WebModel.model:
table_exists.append(table)
#If don't want order
#set([1,2,3,4]) - set([2,5])
tables=list(WebModel.model.keys())
#Array diff ordered
new_tables=[x for x in tables if x not in table_exists]
# Get foreignkeys
# SELECT * FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA='catalogdev_db' AND information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY' ;
foreignkey_fields={}
#| CONSTRAINT_CATALOG | CONSTRAINT_SCHEMA | CONSTRAINT_NAME | TABLE_SCHEMA | TABLE_NAME | CONSTRAINT_TYPE |
#+--------------------+-------------------+-----------------------------------------+---------------+-------------------+-----------------+
#| def | catalogdev_db | product_id_attributesIDX | catalogdev_db | attributes | FOREIGN KEY |
#WebModel.connections
db_name=WebModel.connections['default']['db']
with connection.query('SELECT * FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA=%s AND information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = %s', [db_name, 'FOREIGN KEY']) as cursor:
for row in cursor:
if not row['TABLE_NAME'] in foreignkey_fields:
foreignkey_fields[row['TABLE_NAME']]=[]
foreignkey_fields[row['TABLE_NAME']]=row['CONSTRAINT_NAME'].replace('_{}IDX'.format(row['TABLE_NAME']), '')
pass
#If don't want order
#new_tables=set(tables)-set(table_exists)
#Need order new_tables
changes=0
#Create new tables
if len(new_tables)>0:
print(Style.BRIGHT+"Creating new tables...")
changes+=1
for table in new_tables:
print(Style.NORMAL+"--Creating table "+table+"...")
connection.query(WebModel.model[table].create_table())
for table in new_tables:
print("--Adding indexes and constraints for the new table "+table)
for k_field, index in WebModel.arr_sql_index[table].items():
print("---Added index to "+k_field)
connection.query(index)
for k_set, index_set in WebModel.arr_sql_set_index[table].items():
if index_set!="":
connection.query(index_set)
print("---Added constraint to "+k_set)
print("--Adding uniques elements for the new table")
for k_field, unique_set in WebModel.arr_sql_unique[table].items():
if unique_set!="":
connection.query(unique_set)
print("---Added unique to "+unique_set)
#See if changes exists
#Check if created tables are modified.
try:
model_old=import_module('backups.'+args.model)
for name, obj in inspect.getmembers(sys.modules[model_old.__name__]):
if inspect.isclass(obj):
if obj.__module__=='backups.'+args.model and hasattr(obj, 'webmodel'):
WebModel.model['old_'+name.lower()]=obj(connection)
print(Style.BRIGHT+"Checking old versions of model for find changes...")
for table in tables:
#print(table)
table_fields={table: {}}
# Field | Type | Null | Key | Default | Extra |
#| id | int(11) | NO | PRI | NULL | auto_increment |
with connection.query('describe %s' % table) as cursor:
#all_fields=cursor.fetchall()
#print(all_fields)
for row in cursor:
table_fields[table][row['Field']]={'type': row['Type'], 'key': row['Key']}
pass
#print(table_fields)
#connection.query("")
#Check if new table
#fields_to_add, fields_to_modify, fields_to_add_index, fields_to_add_constraint, fields_to_add_unique, fields_to_delete_index, fields_to_delete_unique, fields_to_delete_constraint, fields_to_delete
fields_to_add=[]
fields_to_modify=[]
fields_to_add_index=[]
fields_to_add_constraint=[]
fields_to_add_unique=[]
fields_to_delete_index=[]
fields_to_delete_unique=[]
fields_to_delete_constraint=[]
fields_to_delete=[]
old_table='old_'+table
if not old_table in WebModel.model:
WebModel.model[old_table]=WebModel.model[table]
for f, v in WebModel.model[table].fields.items():
#if not f in WebModel.model[old_table].fields:
if not f in table_fields[table]:
fields_to_add.append(f)
#Add index
if v.indexed==True:
fields_to_add_index.append(f)
changes+=1
#Add unique
if v.unique==True:
fields_to_add_unique.append(f)
changes+=1
#Add constraint
if v.foreignkey==True:
fields_to_add_constraint.append(f)
changes+=1
changes+=1
#If exists field in old webmodel and new
else:
v_old=WebModel.model[old_table].fields[f]
if v.get_type_sql()!=v_old.get_type_sql():
fields_to_modify.append(f)
changes+=1
#Add index
#if v.indexed==True and v_old.indexed==False:
if v.indexed==True and table_fields[table][f]['key']!='MUL':
fields_to_add_index.append(f)
changes+=1
#if v.indexed==False and v_old.indexed==True:
if v.indexed==False and table_fields[table][f]['key']=='MUL' and v.foreignkey==False:
fields_to_delete_index.append(f)
changes+=1
#Add unique
#if v.unique==True and v_old.unique==False:
if v.unique==True and table_fields[table][f]['key']!='UNI':
fields_to_add_unique.append(f)
changes+=1
#if v.unique==False and v_old.unique==True:
if v.unique==False and table_fields[table][f]['key']=='UNI':
fields_to_delete_unique.append(f)
changes+=1
#Add constraint
#if v.foreignkey==True and v_old.foreignkey==False:
if v.foreignkey==True and table_fields[table][f]['key']!='MUL':
fields_to_add_constraint.append(f)
changes+=1
#if v.foreignkey==False and v_old.foreignkey==True:
if v.foreignkey==False and table_fields[table][f]['key']=='MUL':
if table in foreignkey_fields:
if f in foreignkey_fields[table]:
fields_to_delete_constraint.append(f)
changes+=1
# Clean fields
#for f, v in WebModel.model[old_table].fields.items():
for f, v in table_fields[table].items():
if not f in WebModel.model[table].fields:
#Add constraint
#if v.foreignkey==True:
if table in foreignkey_fields:
if f in foreignkey_fields[table]:
fields_to_delete_constraint.append(f)
changes+=1
fields_to_delete.append(f)
changes+=1
WebModel.model[table].update_table(fields_to_add, fields_to_modify, fields_to_add_index, fields_to_add_constraint, fields_to_add_unique, fields_to_delete_index, fields_to_delete_unique, fields_to_delete_constraint, fields_to_delete)
#for field_update in arr_update:
#Make a for in fields, if the field not exist in old model, create, if is not same type, recreate. If no have index now, delete index, if is a new index, create, same thing with uniques
#for field in WebModel.model
except ImportError:
pass
except:
print("Exception in user code:")
print("-"*60)
traceback.print_exc(file=sys.stdout)
print("-"*60)
exit(1)
original_file_path=args.model.replace('.', '/')+'.py'
backup_path='backups/'+original_file_path
if changes>0:
print(Style.BRIGHT+"Creating backup of the model. WARNING: DON'T DELETE BACKUPS DIRECTORY IF YOU WANT MAKE CHANGES IN THE FUTURE WITHOUT MODIFY DIRECTLY THE DATABASE")
create_backup(original_file_path, backup_path)
else:
if not os.path.isfile(backup_path):
create_backup(original_file_path, backup_path)
# Execute script
arr_script_model=args.model.split('.')
arr_script_model.pop()
script_model='.'.join(arr_script_model)+'.scripts.install'
script_py=script_model.replace('.', '/')+'.py'
if os.path.isfile(script_py):
locked_file='/'.join(arr_script_model)+'/scripts/locked'
if not os.path.isfile(locked_file):
script_install=import_module(script_model)
script_install.run()
f=open(locked_file, 'w')
f.write('OK')
f.close()
connection.close()
#script_model=args.model+''
print(Style.BRIGHT+"All tasks finished")
def create_backup(original_file_path, file_path):
#Create copy
path=os.path.dirname(file_path)
p=Path(path)
if not p.is_dir():
p.mkdir(0o755, True)
with open(path+'/__init__.py', 'w') as f:
f.write("#!/usr/bin/env python3\n")
#Create path
if os.path.isfile(file_path):
today = date.today()
shutil.copy(file_path, file_path+'.'+today.strftime("%Y%M%d%H%M%S"))
new_file=""
f=open(original_file_path)
for line in f:
"""
new_line=line.replace("model[\"", "model[\"old_")
new_line=new_line.replace("model['", "model['old_")
new_line=new_line.replace("WebModel(\"", "WebModel(\"old_")
new_line=new_line.replace("WebModel('", "WebModel('old_")
"""
new_file+=line
f.close()
f=open(file_path, 'w')
f.write(new_file)
f.close()

View file

@ -0,0 +1,18 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""

View file

@ -0,0 +1,98 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.webmodel import PhangoField,WebModel
import json
class ArrayField(PhangoField):
"""Field for save json arrays with determined values"""
def __init__(self, name, field_type, required=False):
"""
Args:
name (str): The name of new field
field_type (PhangoField): The type of PhangoField for save in ArrayField
required (bool): Boolean for define if field is required or not
"""
super().__init__(name, required)
self.field_type=field_type
self.error_default='Sorry, the json array is invalid'
self.set_default='NOT NULL'
self.type_sql='text'
self.jtype='array'
self.default_value='[]'
def check(self, value):
if type(value).__name__=='str':
try:
value=json.loads(value)
except json.JSONDecodeError:
value=[]
self.error=True
self.txt_error=self.error_default
elif type(value).__name__!='list':
value=[]
self.error=True
self.txt_error='Sorry, the json array is invalid'
error=0
if type(self.field_type).__name__!='ArrayField':
for k,v in enumerate(value):
value[k]=self.field_type.check(v)
if self.field_type.error:
error+=1
if error>0:
self.error=True
final_value=json.dumps(value)
final_value=WebModel.escape_sql(final_value)
return final_value
def get_type_sql(self):
return 'TEXT '+self.set_default
def show_formatted(self, value):
return ", ".join(value)
def loads(self, value):
try:
return json.loads(value)
except:
return False

View file

@ -0,0 +1,73 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.corefields import IntegerField
try:
from cuchulu.libraries.db.extraforms.colorform import ColorForm
except:
class ColorForm:
pass
class ColorField(IntegerField):
"""Simple field for save colors in hexadecimal format."""
def __init__(self, name, size=11, required=False):
super().__init__(name, size, required)
self.name_form=ColorForm
self.jtype='string'
self.jexample='#f0f0f0'
def check(self, value):
value=str(value).replace('#', '0x')
value=int(value, 16)
if value<0 or value>0xffffff:
value=0
return value
def get_hex_color(self, value):
value=str(hex(int(value))).replace('0x', '')
c=len(value)
if(c<6):
repeat=6-c
value=('0'*repeat)+value
value='#'+value
return value
def show_formatted(self, value):
value=str(hex(int(value))).replace('0x', '')
c=len(value)
if(c<6):
repeat=6-c
value=('0'*repeat)+value
value='#'+value
return '<div style="width:50px;height:50px;background-color:%s;"></div>' % value;

View file

@ -0,0 +1,67 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.corefields import PhangoField
from cuchulu.libraries import datetime
try:
from cuchulu.libraries.db.extraforms.dateform import DateForm
except:
class DateForm:
pass
class DateField(PhangoField):
"""Field for use and save dates in YYYYMMDDHHSS format"""
def __init__(self, name, size=255, required=False):
super().__init__(name, size, required)
self.name_form=DateForm
self.utc=True
self.error_default='Error: Date format invalid'
self.jtype='string'
self.jformat='date-time'
def check(self, value):
if self.utc:
value=datetime.local_to_gmt(value)
elif not datetime.obtain_timestamp(value):
self.error=True
self.txt_error=self.error_default
return ''
if value==False:
self.error=True
self.txt_error=self.error_default
return ''
return value
def show_formatted(self, value):
return datetime.format_date(value)

View file

@ -0,0 +1,92 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.corefields import PhangoField
from cuchulu.libraries import datetime
try:
from cuchulu.libraries.db.extraforms.dateform import DateForm
except:
class DateForm:
pass
class DateTimeField(PhangoField):
"""Field for use and save dates in MySQL date format"""
def __init__(self, name, size=255, required=False):
super().__init__(name, size, required)
self.name_form=DateForm
self.utc=False
self.error_default='Error: Date format invalid'
self.type_sql='datetime'
self.jformat='date-time'
self.jtype='string'
self.jexample='2022-12-01 12:24:11'
def check(self, value):
if self.utc:
value=datetime.local_to_gmt(value)
elif not datetime.obtain_timestamp(value):
self.error=True
self.txt_error=self.error_default
return '0000-00-00 00:00:00'
if value==False:
self.error=True
self.txt_error=self.error_default
return '0000-00-00 00:00:00'
else:
"""
format_date_txt="YYYY/MM/DD"
format_time_txt="HH:mm:ss"
"""
value=datetime.format_local_strtime('YYYY-MM-DD HH:mm:ss', value)
return value
def show_formatted(self, value):
# Convert to paramecio value
value=str(value)
value=value.replace('-', '').replace(':', '').replace(' ', '')
return datetime.format_date(value)
def get_type_sql(self):
"""Method for return the sql code for this type
"""
return 'DATETIME NOT NULL'

View file

@ -0,0 +1,87 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.webmodel import WebModel, PhangoField
import json
class DictField(PhangoField):
"""Field for save json dicts with determined values"""
def __init__(self, name, field_type, required=False):
"""
Args:
name (str): The name of field
field_type (PhangoField): The type of PhangoField for save in ArrayField
required (bool): Boolean for define if field is required or not
"""
super().__init__(name, required)
self.field_type=field_type
self.error_default='Sorry, the json dict is invalid'
self.set_default='NOT NULL'
self.type_sql='longtext'
self.jtype='object'
self.default_value='{}'
def check(self, value):
if type(value).__name__=='str':
try:
value=json.loads(value)
except json.JSONDecodeError:
value={}
self.error=True
self.txt_error=self.error_default
elif type(value).__name__!='dict':
value={}
self.error=True
self.txt_error=self.error_default
error=0
for k,v in value.items():
value[k]=self.field_type.check(v)
if self.field_type.error:
error+=1
final_value=json.dumps(value)
if error>0:
self.error=True
#final_value=WebModel.escape_sql(final_value)
return final_value
def get_type_sql(self):
return 'JSON '+self.set_default
def show_formatted(self, value):
return ", ".join(value)

View file

@ -0,0 +1,49 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.corefields import CharField
import re
mail_pattern=re.compile(r"\w[\w\.-]*@\w[\w\.-]+\.\w+")
class EmailField(CharField):
"""Field for save and check email addreses"""
def __init__(self, name, size=1024, required=False):
super().__init__(name, size, required)
self.error_default='Error: No valid format'
self.jformat='email'
def check(self, value):
value=super().check(value)
self.error=False
self.txt_error=''
if not mail_pattern.match(value):
self.error=True
value=""
self.txt_error=self.error_default
return value

View file

@ -0,0 +1,210 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import os
import sys
from pathlib import Path
from cuchulu.libraries.db.corefields import CharField
from cuchulu.libraries.db.extraforms.fileform import FileForm
#from paramecio.citoplasma import httputils
from cuchulu.libraries.keyutils import create_key
import traceback
from bottle import request
#from flask import request
#from werkzeug.utils import secure_filename
from uuid import uuid4
#from cuchulu.libraries.db.extraforms.fileform import FileForm
class FileField(CharField):
"""Field for upload and save files in server"""
def __init__(self, name, save_folder='media/upload/files', sizes=None, size=255, required=False):
"""
Args:
name (str): The name of field
save_folder (str): The folder where the files are saved
sizes (list): In the future will be used for check sizes of files.
size (int): The size of the new field in database. By default 11.
required (bool): Boolean for define if field is required or not
"""
super().__init__(name, size, required)
self.yes_prefix=True
self.suffix=''
# Is relative to media folder of paramecio
#if module!=None:
self.save_folder=save_folder
self.file_related=True
self.sizes=sizes
self.name_form=FileForm
self.extra_parameters=[self.save_folder]
def change_folder(self, folder):
pass
def check(self, value):
files_uploaded=request.files
field_file=self.name+'_file'
#if not change
if not field_file in files_uploaded:
if value=='':
if self.model:
if self.model.updated:
old_reset=self.model.yes_reset_conditions
self.model.yes_reset_conditions=False
with self.model.select([self.name]) as cur:
for arr_image in cur:
if arr_image[self.name]!='':
try:
os.remove(arr_image[self.name])
except:
pass
#if arr_image[self.name]!=save_file and arr_image[self.name]!='':
#value=arr_image[self.name]
self.model.yes_reset_conditions=old_reset
self.txt_error='Field is empty'
self.error=True
return ''
else:
value=os.path.basename(value)
return self.save_folder+'/'+value
# Load image file
#file_bytecode=files_uploaded[field_file].file
filename=files_uploaded[field_file].filename
realfilename, ext = os.path.splitext(filename)
prefix=''
if self.yes_prefix==True:
#prefix=uuid4().hex+'_'
prefix=create_key(5).replace('/', '-').replace('#', '-')+self.suffix+'_'
filename=prefix+filename
save_file=self.save_folder+'/'+filename
# Save file
try:
#Check if directory exists
if not os.path.isdir(self.save_folder):
# Try create if not
try:
p=Path(self.save_folder)
p.mkdir(mode=0o755, parents=True)
except:
self.error=True
self.txt_error='Error: cannot create the directory where save the image.Check permissions,'
return ""
#files_uploaded[field_file].save(self.save_folder, overwrite=True)
if os.path.isfile(save_file):
os.remove(save_file)
# Delete old files
if self.model!=None:
if self.model.updated:
#old_conditions=self.model.conditions
old_reset=self.model.yes_reset_conditions
self.model.yes_reset_conditions=False
with self.model.select([self.name]) as cur:
for arr_file in cur:
if arr_file[self.name]!=save_file and arr_file[self.name]!='':
if os.path.isfile(arr_file[self.name]):
os.remove(arr_file[self.name])
self.model.yes_reset_conditions=old_reset
# Save file
files_uploaded[field_file].save(save_file)
#self.model.conditions=old_conditions
return save_file
except:
self.error=True
self.txt_error='Error: cannot save the image file, Exists directory for save the file? '+traceback.format_exc()
print(traceback.format_exc())
return ""
def show_formatted(self, value):
return os.path.basename(value)

View file

@ -0,0 +1,184 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import json
from cuchulu.libraries.db.webmodel import PhangoField
from cuchulu.libraries.db.coreforms import BaseForm
from cuchulu.libraries.db.extraforms.i18nform import I18nForm
from cuchulu.libraries.i18n import I18n
#from paramecio.citoplasma.httputils import GetPostFiles
import json
import re
class I18nField(PhangoField):
"""Field for save strings multilanguage in json format"""
def __init__(self, name, form=None):
"""
Args
name (str): The name of field
form (BaseForm): The form used for generate the multiple languade form. Example if you use a TextForm, a TextForm for every language will be showed.
"""
super().__init__(name)
if form==None:
form=BaseForm(name, '')
self.name_form=I18nForm
self.extra_parameters=[form]
self.show_formatted_value=True
self.show_blank=False
arr_i18n={i:'' for i in I18n.dict_i18n}
self.default_value=json.dumps(arr_i18n)
self.type_sql='longtext'
def change_form(self, form):
self.extra_parameters=[form]
def check_value(self, value):
return super().check(value)
def check(self, value):
self.error=False
self.txt_error=''
arr_values={}
try:
arr_values=json.loads(value)
if not arr_values:
arr_values={}
except:
arr_values={}
arr_real_values={}
error_values=0
for lang in I18n.dict_i18n:
arr_real_values[lang]=arr_values.get(lang, '')
arr_real_values[lang]=self.check_value(arr_real_values[lang])
if not arr_real_values[lang] or arr_real_values[lang]=='None':
arr_real_values[lang]=''
error_values+=1
self.error=False
arr_values=arr_real_values
if error_values:
if error_values==len(arr_values):
self.error=True
self.txt_error='Sorry, You field language is empty'
return json.dumps(arr_values)
"""
if arr_values[I18n.default_lang]=='':
self.error=True
self.txt_error='Sorry, You need default language '+I18n.default_lang
return json.dumps(arr_values)
"""
return json.dumps(arr_values)
def get_type_sql(self):
return 'JSON NOT NULL'
def obtain_lang_value(self, lang, value):
return value.get(self.name+'_'+lang, '')
def obtain_lang_from_post(self, lang, value):
#getpost=GetPostFiles()
#getpost.obtain_post()
return "" #GetPostFiles.post.get(self.name+'_'+lang, '')
def show_formatted(self, value):
if value=='':
value='{"en-US": "", "es-ES": ""}'
value=json.loads(value)
lang=I18n.get_default_lang()
if value[lang]!='' or self.show_blank:
return value[lang]
lang_value=value[I18n.default_lang]
if value[I18n.default_lang]=='':
for l in value:
if value[l]!='':
lang_value=value[l]
break
return lang_value
@staticmethod
def get_value(value):
value=json.loads(value)
lang=I18n.get_default_lang()
if value[lang]!='':
return value[lang]
return value[I18n.default_lang]
class I18nHTMLField(I18nField):
def check_value(self, value):
return re.sub('<.*?script?>', '', value)
class I18nPhangoField(I18nField):
def __init__(self, name, field_class, form=None):
super().__init__(name, form)
self.field_class=field_class
def check_value(self, value):
f=self.field_class
return f.check(value)

View file

@ -0,0 +1,332 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import os
import sys
from pathlib import Path
from cuchulu.libraries.db.corefields import CharField
from cuchulu.libraries.db.extraforms.fileform import FileForm
from cuchulu.libraries.keyutils import create_key
import traceback
#from flask import request
#from werkzeug.utils import secure_filename
from bottle import request
# from bottle import request
try:
from PIL import Image
except:
print("Unexpected error:", sys.exc_info()[0])
raise
from uuid import uuid4
#from cuchulu.libraries.db.extraforms.fileform import FileForm
class ImageField(CharField):
"""Field for upload images in gif, jpg and png formats"""
def __init__(self, name, save_folder='media/upload/images', sizes=None, module=None, size=255, required=False):
"""
Args:
name (str): The name of field
save_folder (str): The folder where the images are saved
sizes (list): In the future will be used for check sizes of files.
size (int): The size of the new field in database. By default 11.
required (bool): Boolean for define if field is required or not
"""
super().__init__(name, size, required)
self.yes_prefix=True
#self.name_form=FileForm
self.thumbnail={'mini_': 150}
self.yes_thumbnail=False
self.default_quality_thumb=95
self.suffix=''
# Is relative to media folder of paramecio
#if module!=None:
self.save_folder=save_folder
self.file_related=True
self.sizes=sizes
self.name_form=FileForm
self.extra_parameters=[self.save_folder]
def change_folder(self, folder):
pass
def check(self, value):
files_uploaded=request.files
field_file=self.name+'_file'
#if not change
if field_file in files_uploaded:
if files_uploaded[field_file].filename=='':
if value=='':
if self.model:
if self.model.updated:
old_reset=self.model.yes_reset_conditions
self.model.yes_reset_conditions=False
with self.model.select([self.name]) as cur:
for arr_image in cur:
if arr_image[self.name]!='':
try:
os.remove(arr_image[self.name])
except:
pass
#if arr_image[self.name]!=save_file and arr_image[self.name]!='':
#value=arr_image[self.name]
self.model.yes_reset_conditions=old_reset
self.txt_error='Field is empty'
self.error=True
return ''
else:
value=os.path.basename(value)
return self.save_folder+'/'+value
else:
self.txt_error='Field is empty'
self.error=True
return ''
#value=os.path.basename(value)
#return self.save_folder+'/'+value
# Load image file
#file_bytecode=files_uploaded[field_file].file
filename=files_uploaded[field_file].filename
try:
im=Image.open(files_uploaded[field_file])
except IOError:
self.error=True
self.txt_error='Error, file not have a valid format'
return ""
real_width=im.size[0]
real_height=im.size[1]
if self.sizes:
if 'maximum' in self.sizes:
if self.sizes['maximum'][0]<real_width or self.sizes['maximum'][1]<real_height:
self.error=True
self.txt_error='Wrong size. Maximum size is '+str(self.sizes['maximum'][0])+'x'+str(self.sizes['maximum'][1])
im.close()
return ""
if 'minimum' in self.sizes:
if self.sizes['minimum'][0]>real_width or self.sizes['minimum'][1]>real_height:
self.error=True
self.txt_error='Wrong size. Minimum size is '+str(self.sizes['minimum'][0])+'x'+str(self.sizes['minimum'][1])
im.close()
return ""
if 'resize' in self.sizes:
height_t=0
width_t=0
if real_height<=self.sizes['resize'][1]:
height_t=self.sizes['resize'][1]
if real_width>self.sizes['resize'][0]:
width_t=self.sizes['resize'][0]
if height_t==0:
ratio=(real_width/width_t)
height_t=round(real_height/ratio)
size=(width_t, height_t)
if width_t>0 and height_t>0:
im.thumbnail(size, 3)
format_image=im.format
if format_image!='JPEG' and format_image!='GIF' and format_image!='PNG':
self.error=True
self.txt_error='Format is wrong. Requires GIF, JPEG or PNG formats'
im.close()
return ""
# Create thumbnails and move file
realfilename, ext = os.path.splitext(filename)
prefix=''
if self.yes_prefix==True:
#prefix=uuid4().hex+'_'
prefix=create_key(5).replace('/', '-').replace('#', '-')+self.suffix+'_'
filename=prefix+filename
save_file=self.save_folder+'/'+filename
# Save file
try:
#Check if directory exists
if not os.path.isdir(self.save_folder):
# Try create if not
try:
p=Path(self.save_folder)
p.mkdir(mode=0o755, parents=True)
except:
im.close()
self.error=True
self.txt_error='Error: cannot create the directory where save the image.Check permissions,'
return ""
#files_uploaded[field_file].save(self.save_folder, overwrite=True)
if os.path.isfile(save_file):
os.remove(save_file)
# Save thumbnails
if self.yes_thumbnail:
for name, width_t in self.thumbnail.items():
im_thumb=im.copy()
ratio=(real_width/width_t)
height_t=round(real_height/ratio)
size=(width_t, height_t)
save_file_thumb=self.save_folder+'/'+name+filename
im_thumb.thumbnail(size, Image.LANCZOS)
im_thumb.save(save_file_thumb, "JPEG", quality=self.default_quality_thumb)
im_thumb.close()
im.save(save_file)
# Delete old files
if self.model!=None:
if self.model.updated:
#old_conditions=self.model.conditions
old_reset=self.model.yes_reset_conditions
self.model.yes_reset_conditions=False
with self.model.select([self.name]) as cur:
for arr_image in cur:
if arr_image[self.name]!=save_file and arr_image[self.name]!='':
if os.path.isfile(arr_image[self.name]):
os.remove(arr_image[self.name])
if self.yes_thumbnail:
for tname, width_t in self.thumbnail.items():
old_dir_name=os.path.dirname(arr_image[self.name])
old_base_name=os.path.basename(arr_image[self.name])
old_thumb_name=old_dir_name+'/'+tname+old_base_name
if os.path.isfile(old_thumb_name):
os.remove(old_thumb_name)
self.model.yes_reset_conditions=old_reset
#self.model.conditions=old_conditions
im.close()
return save_file
except:
im.close()
self.error=True
self.txt_error='Error: cannot save the image file, Exists directory for save the file? '+traceback.format_exc()
print(traceback.format_exc())
return ""
def show_formatted(self, value):
return os.path.basename(value)

View file

@ -0,0 +1,45 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.corefields import CharField
import ipaddress
class IpField(CharField):
"""Field for save ip internet address values in db"""
def __init__(self, name, size=1024, required=False):
super().__init__(name, size, required)
self.jformat='ipV4'
def check(self, value):
try:
value=str(ipaddress.ip_address(value))
except:
self.error=True
self.txt_error='No Valid IP'
value=""
return value

View file

@ -0,0 +1,119 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.webmodel import WebModel, PhangoField
import sys
try:
import ujson as json
except:
import json
class JsonField(PhangoField):
"""Field for save json datatype values"""
def __init__(self, name, field_type, required=False):
"""
Args:
name (str): The name of field
field_type (PhangoField): The type of PhangoField for save in JsonField
required (bool): Boolean for define if field is required or not
"""
super().__init__(name, required)
self.field_type=field_type
self.error_default='Sorry, the json dict is invalid'
self.set_default='NOT NULL'
self.type_sql='longtext'
self.jtype='object'
def check(self, value):
if type(value).__name__=='str':
try:
value=json.loads(value)
except json.JSONDecodeError:
value={}
self.error=True
self.txt_error=self.error_default
elif type(value).__name__!='dict':
value={}
self.error=True
self.txt_error=self.error_default
for k,v in value.items():
value[k]=self.field_type.check(v)
final_value=json.dumps(value)
#final_value=WebModel.escape_sql(final_value)
return final_value
def get_type_sql(self):
return 'JSON '+self.set_default
def show_formatted(self, value):
return ", ".join(value)
# You need check the values previously.
class JsonValueField(PhangoField):
"""Field for save json mixed values. You need check the values previously, the field only check values for prevent sql injections."""
def __init__(self, name, required=False):
super().__init__(name, required)
self.error_default='Sorry, the json dict is invalid'
self.default_value={}
#self.set_default='NOT NULL'
def get_type_sql(self):
return 'JSON'
def check(self, value):
#print(value)
try:
final_value=json.dumps(value)
final_value=value
except json.JSONDecodeError:
final_value='{}'
self.error=True
self.txt_error=self.error_default
return final_value

View file

@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.corefields import CharField
from cuchulu.libraries.db import coreforms
from cuchulu.libraries.i18n import I18n
class LangField(CharField):
"""Field for save language codes, by default es-ES (spanish) and en-US (USA english)"""
def __init__(self, name, size=255, required=False):
super(CharField, self).__init__(name, size, required)
select_lang={}
for lang in I18n.dict_i18n:
select_lang[lang]=lang
self.change_form(coreforms.SelectForm, [select_lang])
self.default_value=I18n.default_lang
def check(self, value):
if value not in I18n.dict_i18n:
value=I18n.default_lang
return value

View file

@ -0,0 +1,51 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.corefields import DecimalField
from decimal import Decimal, getcontext
from locale import format_string
getcontext().prec=2
class MoneyField(DecimalField):
"""Field for maintain money values for e-commerce shopping for example."""
def __init__(self, name, required=False):
super().__init__(name, 11, required)
def check(self, value):
try:
value=Decimal(value)
except:
value=0
return value
def show_formatted(self, value):
return format_string('%.2f', Decimal(value), grouping=True)
@staticmethod
def format_money(value):
return format_string('%.2f', Decimal(value), grouping=True)

View file

@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
#from cuchulu.libraries.db.webmodel import PhangoField
from cuchulu.libraries.db.corefields import IntegerField
from cuchulu.libraries.db.coreforms import SelectModelForm
#from paramecio.citoplasma.httputils import GetPostFiles
#from flask import request
from bottle import request
class ParentField(IntegerField):
"""Field used for create fields used by save a parent id from a row in db."""
def __init__(self, name, size=11, required=False, field_name='name'):
"""
Args:
name (str): The name of field
size (int): The size of the new field in database. By default 11.
required (bool): Boolean for define if field is required or not
field_name (str): The name of the field used for identify the father row of the db.
"""
super().__init__(name, size, required)
#self.foreignkey=True
self.indexed=True
self.field_name=field_name
def post_register(self):
if self.model!=None:
self.change_form(SelectModelForm, [self.model, self.field_name, self.model.name_field_id, self.name])
def check(self, value):
value=super().check(value)
if self.model!=None:
if self.model.updated==True:
if self.model.name_field_id in self.model.post:
#GetPostFiles.obtain_get()
#model_id=GetPostFiles.get.get(self.model.name_field_id, '0')
model_id=request.query.get(self.model.name_field_id, '0')
if model_id==value:
self.error=True
self.txt_error='A field cannot be its own father'
self.required=True
value=0
return value
return value

View file

@ -0,0 +1,155 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.corefields import PhangoField
from cuchulu.libraries.db.coreforms import PasswordForm
from hmac import compare_digest as compare_hash
#try:
# import crypt
#except:
# pass
#import bcrypt
from argon2 import PasswordHasher
class PasswordField(PhangoField):
"""Field for check and save passwords"""
def __init__(self, name, size=1024, required=False):
super(PasswordField, self).__init__(name, size, required)
self.protected=True
self.name_form=PasswordForm
self.default_value=''
self.encrypt_password=True
self.jformat='password'
def check(self, value):
self.txt_error=''
self.error=False
value.strip()
if value=='':
if self.model!=None:
if self.model.updated==True:
self.required=False
self.check_blank=True
return ""
else:
self.txt_error=self.error_default
self.error=True
else:
self.txt_error=self.error_default
self.error=True
else:
#if crypt.METHOD_SHA512 in crypt.methods:
#salt=crypt.mksalt(crypt.METHOD_SHA512)
if self.encrypt_password:
#value=crypt.crypt(value)
ph=PasswordHasher()
final_value=ph.hash(value)
return final_value
"""
else:
self.txt_error="You need the SHA512 method"
self.error=True
return ""
"""
return value
@staticmethod
def verify( password, h):
"""Static method used for verify a password save using PasswordField"""
#return bcrypt_sha256.verify(password, h)
#return compare_hash(h, crypt.crypt(password, h))
ph=PasswordHasher()
try:
return ph.verify(h, password)
except:
return False
# Old function bcrypt
"""
try:
from passlib.hash import bcrypt
from passlib.hash import bcrypt_sha256
class PasswordField(PhangoField):
def __init__(self, name, size=1024, required=False):
super(PasswordField, self).__init__(name, size, required)
self.protected=True
self.name_form=PasswordForm
self.default_value=''
def check(self, value):
self.txt_error=''
self.error=False
value.strip()
if value=='':
if self.model!=None:
if self.model.updated==True:
self.required=False
self.check_blank=True
return ""
else:
self.txt_error="The field is empty"
self.error=True
else:
self.txt_error="The field is empty"
self.error=True
else:
#if crypt.METHOD_SHA512 in crypt.methods:
#value = bcrypt_sha256.encrypt(value)
value = bcrypt_sha256.hash(value)
return value
@staticmethod
def verify( password, h):
return bcrypt_sha256.verify(password, h)
except:
"""

View file

@ -0,0 +1,42 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.corefields import DecimalField
class PercentField(DecimalField):
"""Field used for save percent values from 0 to 100."""
def __init__(self, name, required=False):
super().__init__(name, 2, required)
def check(self, value):
try:
value=int(value)
if value<0:
value=0
if value>100:
value=100
except:
value=0
return value

View file

@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.corefields import CharField
from slugify import slugify
from cuchulu.libraries.db.coreforms import HiddenForm
class SlugifyField(CharField):
"""Field for process text and slugify it"""
def __init__(self, name, size=255, field_related=None, required=False):
super(SlugifyField, self).__init__(name, size, required)
self.name_form=HiddenForm
self.field_related=field_related
def check(self, value):
value=slugify(value)
if value=='':
if self.model!=None and self.field_related!=None:
self.model.post[self.field_related]=self.model.post.get(self.field_related, '')
value=slugify(self.model.post[self.field_related])
if value=='':
self.error=True
self.error_txt='Value is empty'
return ''
return value

View file

@ -0,0 +1,99 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.corefields import CharField
import re
import ipaddress
check_url = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
r'localhost|' #localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
class UrlField(CharField):
"""Field for check and save strings in url format"""
def __init__(self, name, size=1024, required=False):
super().__init__(name, size, required)
self.jformat='url'
def check(self, value):
self.error=False
self.txt_error=''
if not check_url.match(value):
self.error=True
value=""
self.txt_error='No valid URL format'
return value
check_domain=re.compile(r'^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$')
class DomainField(CharField):
"""Field for check and save strings in domain internet format"""
def check(self, value):
self.error=False
self.txt_error=''
if not check_domain.match(value):
#Check if ip
try:
value=str(ipaddress.ip_address(value))
except:
self.error=True
value=""
self.txt_error='No valid domain or IP format'
return value
#^(https|ssh):\/\/([a-zA-Z0-9\-_]+@)?[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*(:[0-9]+)?\/[a-zA-Z0-9\-_]+(\/[a-zA-Z0-9\-_]+)*(\.git)?$
check_git_url=re.compile(r'^(https|ssh):\/\/([a-zA-Z0-9\-_]+@)?[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*(:[a-zA-Z0-9\-_]+)?\/[a-zA-Z0-9\-_]+(\/[a-zA-Z0-9\-_]+)*(\.git)?$')
class GitUrlField(CharField):
"""Field for check and save strings in url format for git services"""
def check(self, value):
self.error=False
self.txt_error=''
value=value.strip()
if not check_git_url.match(value):
self.error=True
value=""
self.txt_error='No valid Git URL format'
return value

View file

@ -0,0 +1,37 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.corefields import PhangoField
from cuchulu.libraries.db.coreforms import PasswordForm
from hmac import compare_digest as compare_hash
#import crypt
import re
class UserNameField(PhangoField):
"""Field for save and check usernames"""
def check(self, value):
if not re.match("^[A-Za-z0-9_-]+$", value):
self.txt_error='Error: use only letters, numbers, underscores and dashes for this field'
self.error=1
value=''
return value

View file

@ -0,0 +1,18 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""

View file

@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.coreforms import BaseForm
class CheckForm(BaseForm):
"""Checkbox form, used normally with boolean fields"""
def __init__(self, name, value, real_value=1):
"""
Args:
name (str): The html name for this form
value (str): The default value of this html form.
real_value (str): Variable used for construct the html form, by default 1.
"""
super(CheckForm, self).__init__(name, value)
self.real_value=real_value
def form(self):
arr_value={}
arr_value[self.setform(self.default_value)]=''
arr_value[self.setform(self.real_value)]='checked'
return '<input type="checkbox" class="'+self.css+'" name="'+self.name+'" id="'+self.name_field_id+'" value="'+str(self.real_value)+'" '+arr_value[self.setform(self.default_value)]+'>'

View file

@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.coreforms import BaseForm
from cuchulu.libraries.mtemplates import standard_t
class ColorForm(BaseForm):
"""Form for get colors from a picker"""
def __init__(self, name, value):
super().__init__(name, value)
self.t=standard_t
def form(self):
return self.t.load_template('forms/colorform.phtml', name_form=self.name_field_id, default_value=self.default_value, form=self)

View file

@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.coreforms import BaseForm
from cuchulu.libraries.mtemplates import standard_t
from cuchulu.libraries.datetime import format_timedata
class DateForm(BaseForm):
"""Create a form for dates, with year, day, hour, minut and seconds"""
def __init__(self, name, value):
super().__init__(name, value)
self.yes_time=True
self.t=standard_t
def form(self):
if type(self.default_value).__name__!='datetime':
y=''
m=''
d=''
h=''
min=''
s=''
min_time=''
time=format_timedata(self.default_value)
if time[0]:
y=int(time[0])
m=int(time[1])
d=int(time[2])
h=int(time[3])
min_time=int(time[4])
s='00' #int(time[5])
else:
y=self.default_value.year #"{:>10}".format(s)
m="{:02d}".format(self.default_value.month)
d="{:02d}".format(self.default_value.day)
h="{:02d}".format(self.default_value.hour)
min_time="{:02d}".format(self.default_value.minute)
s='00'
pass
return self.t.load_template('forms/dateform.phtml', yes_time=self.yes_time, form=self.name, y=y, m=m, d=d, h=h, min=min_time, s=s)
#def

View file

@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.coreforms import BaseForm
from cuchulu.libraries.mtemplates import env_theme, PTemplate
env=env_theme(__file__)
t=PTemplate(env)
class FileForm(BaseForm):
"""Class for create a form for upload files. You shoud set enctype to True in your model for it"""
def __init__(self, name, value, path):
"""
Args:
name (str): The html name for this form
value (str): The default value of this html form.
path (str): The path where the file will be saved.
"""
super().__init__(name, value)
self.t=t
self.enctype=True
def form(self):
return self.t.load_template('forms/fileform.phtml', form=self)

View file

@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.coreforms import BaseForm
from cuchulu.libraries.i18n import I18n
from cuchulu.libraries.mtemplates import standard_t
import json
class I18nForm(BaseForm):
"""Form for data with multiple languages."""
def __init__(self, name, value, form):
"""
Args:
name (str): The html name for this form
value (str): The default value of this html form.
form (BaseForm): The form used for generate the multiple languade form. Example if you use a TextForm, a TextForm for every language will be showed.
"""
super().__init__(name, value)
self.form_child=form
self.t=standard_t
def form(self):
lang_selected=I18n.get_default_lang()
try:
self.default_value=json.loads(self.default_value)
except:
self.default_value={}
if type(self.default_value).__name__!='dict':
self.default_value={}
for lang in I18n.dict_i18n:
self.default_value[lang]=self.default_value.get(lang, '')
return standard_t.load_template('forms/i18nform.phtml', name_form=self.name_field_id, real_name_form=self.name, form=self.form_child, arr_i18n=I18n.dict_i18n, lang_selected=lang_selected, default_value=self.default_value)

View file

@ -0,0 +1,47 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.coreforms import BaseForm
from cuchulu.libraries.mtemplates import env_theme, PTemplate
env=env_theme(__file__)
t=PTemplate(env)
class TextHTMLForm(BaseForm):
"""Form for html texts, based in tinycme javascript library"""
def __init__(self, name, value, t_add=None):
"""
Args:
name (str): The html name for this form
value (str): The default value of this html form.
t_add (PTemplate): If you want change the standard html form, use other template loader
"""
super().__init__(name, value)
self.t=t_add
if t_add==None:
self.t=t
def form(self):
return self.t.load_template('forms/texthtmlform.phtml', form=self)

View file

@ -0,0 +1,40 @@
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db.coreforms import BaseForm
from cuchulu.libraries.mtemplates import env_theme, PTemplate
env=env_theme(__file__)
t=PTemplate(env)
class TextHTMLForm(BaseForm):
def __init__(self, name, value, t_add=None):
super().__init__(name, value)
self.t=t_add
if t_add==None:
self.t=t
def form(self):
return self.t.load_template('forms/texthtmlform.phtml', form=self)

View file

@ -0,0 +1,278 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for bottle, mako and others and construct a simple headless cms.
Copyright (C) 2024 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.db import corefields
from cuchulu.libraries.db.coreforms import PasswordForm
from cuchulu.libraries.i18n import I18n
from cuchulu.libraries.sessionplugin import get_session
from cuchulu.libraries.keyutils import create_key_encrypt
from bottle import request, abort
# Need unittest
"""Functions and classes for process forms"""
def pass_values_to_form(post, arr_form, yes_error=True, pass_values=True):
"""Function for pass a dict with form values for check using forms dict
Values dict and Forms dict need have the same key. A forms dict is maked of a serie of cuchulu2 forms elements, used for check the value.
Args:
post (dict): Dict composed by a series of values. The keys need to be equal to keys of arr_form dict.
arr_form (dict): Dict composed by a series or forms objects. The keys need to be equal to keys of post dict.
yes_error (bool): Show errors in txt_error form variables.
pass_values (bool): Pass default values or values from post dict to arr_form dict items
Returns:
arr_form (dict): Return arr_form dict with checked values from post dict.
"""
if pass_values:
def get_value(key):
return post[key]
else:
def get_value(key):
return arr_form[key].default_value
for key, value in arr_form.items():
post[key]=post.get(key, '')
#if arr_form[key].default_value=='':
arr_form[key].default_value=get_value(key)
if arr_form[key].field==None:
arr_form[key].field=corefields.CharField(key, 255, required=False)
# Recheck value if no set error field
if arr_form[key].field.error == None:
arr_form[key].field.check(post[key])
#arr_form[key].txt_error=""
if arr_form[key].required==True and arr_form[key].field.error==True and yes_error==True:
arr_form[key].txt_error=arr_form[key].field.txt_error
# Reset error on field.
arr_form[key].field.error=None
return arr_form
class CheckForm():
"""Simple class for make similar check to pass_values_to_form. More simple.
"""
def __init__(self):
self.error=0
def check(self, post, arr_form):
"""Simple method for pass a dict with form values for check using forms dict
Values dict and Forms dict need have the same key. A forms dict is maked of a serie of cuchulu2 forms elements, used for check the value.
Args:
post (dict): Dict composed by a series of values. The keys need to be equal to keys of arr_form dict.
arr_form (dict): Dict composed by a series or forms objects. The keys need to be equal to keys of post dict.
Returns:
post (dict): Return post dict with values checked
arr_form (dict): Return arr_form with errors and values.
"""
for k in arr_form.keys():
post[k]=post.get(k, '')
if arr_form[k].field==None:
arr_form[k].field=corefields.CharField(k, 255, required=False)
post[k]=arr_form[k].field.check(post[k])
arr_form[k].txt_error=arr_form[k].field.txt_error
if arr_form[k].field.error==True and arr_form[k].required==True:
self.error+=1
return post, arr_form
def check_form(post, arr_form, sufix_form='_error'):
"""Function for make check form, passing errors to extra dict called error_form. Also returns an bool variable setting error.
Args:
post (dict): Dict composed by a series of values. The keys need to be equal to keys of arr_form dict.
arr_form (dict): Dict composed by a series or forms objects. The keys need to be equal to keys of post dict.
sufix_form (str): Define the sufix of error_form keys
Returns:
error (bool): Return False if not errors in checking, if errors return True
error_form (dict): A dict containing the errors in form fields.
post (dict): Sanitized values
arr_form (dict): arr_form with errors and values.
"""
error=0
error_form={}
for k in arr_form.keys():
post[k]=post.get(k, '')
if arr_form[k].field==None:
arr_form[k].field=corefields.CharField(k, 255, required=False)
post[k]=arr_form[k].field.check(post[k])
arr_form[k].txt_error=arr_form[k].field.txt_error
if arr_form[k].field.error==True and arr_form[k].required==True:
error_form['#'+k+sufix_form]=arr_form[k].txt_error
error+=1
return error, error_form, post, arr_form
def show_form(post, arr_form, t, yes_error=True, pass_values=True, modelform_tpl='forms/modelform.phtml'):
# Create csrf_token in session
"""Function for generate a html form from a template
Args:
post (dict): Dict composed by a series of values. The keys need to be equal to keys of arr_form dict.
arr_form (dict): Dict composed by a series or forms objects. The keys need to be equal to keys of post dict.
t (PTemplate): Object used for load template for form
yes_error (bool): Show errors in txt_error form variables.
pass_values (bool): Pass default values or values from post dict to arr_form dict items
modelform_tpl (str): Path for the template that generate the html form. By default is cuchulu2/libraries/templates/forms/modelform.phtml
Returns:
template (str): An html string with the generated form.
"""
generate_csrf()
if pass_values==True:
pass_values_to_form(post, arr_form, yes_error, pass_values)
return t.load_template(modelform_tpl, forms=arr_form)
def extract_post(post, fields):
"""Helper function for create a simple array from other using fields list for filter
Args:
post (dict): A dict with keys and values to filter.
fields (list): A list with keys to validate.
"""
return {k:v for k,v in post.items() if k in fields}
#Simple Function for add repeat_password form to user model
def set_extra_forms_user(user_admin):
"""Helper function for add extraforms to UserModel form, not for general use
Args:
user_admin (UserModel): Instance of UserModel object for modify forms and fields
"""
user_admin.fields['password'].required=True
user_admin.fields['email'].required=True
user_admin.create_forms(['username', 'email', 'password'])
user_admin.forms['repeat_password']=PasswordForm('repeat_password', '')
user_admin.forms['repeat_password'].required=True
user_admin.forms['repeat_password'].label=I18n.lang('common', 'repeat_password', 'Repeat Password')
#Function for initial values for necessary fields.
def ini_fields(fields):
pass
def csrf_token(token_id='csrf_token'):
"""Function for generate a csrf token html hide form using flask sessions
Args:
token_id (str): Name of the html hide form
Returns:
html (str): Return html input hidden with csrf token saved in session
"""
s=get_session()
#if not 'csrf_token' in s:
s['csrf_token']=create_key_encrypt()
#s.save()
return '<input type="hidden" name="csrf_token" class="csrf_token" id="'+token_id+'" value="'+s['csrf_token']+'" />'
def generate_csrf():
"""Function for generate a csrf token in a variable
Returns:
csrf_token (str): csrf token value
"""
s=get_session()
if not 'csrf_token' in s:
s['csrf_token']=create_key_encrypt()
#s.save()
return s['csrf_token']
def request_type():
"""Simple shortcut for get the request_type"""
return request.environ['REQUEST_METHOD']
def check_csrf(name_csrf_token='csrf_token'):
"""Function for check the csrf token
Args:
name_csrf_token (str): Name of the csrf_token in session
"""
session=get_session()
csrf_token=session.get(name_csrf_token, '')
if csrf_token=='' or csrf_token!=request.forms.get(name_csrf_token):
abort(403)

View file

@ -0,0 +1,328 @@
#!/usr/bin/env python3
from collections import OrderedDict
import sys
def query(model, str_query, args=[], connection_id='default'):
model.connect_to_db()
return model.sqlclass.query(str_query, args, connection_id)
# Insert method, for insert a row in database.using a dictionary
# External agent define if the update is in code or from external source, how a form.
def insert(model, dict_values, external_agent=True):
model.clean_fields()
# Connect to db
model.post=dict_values
#model.connect_to_db()
query_error=False
last_sql=''
#model.fields[model.name_field_id].required=False
if model.name_field_id in dict_values:
del dict_values[model.name_field_id]
try:
fields, values, update_values=model.check_all_fields(dict_values, external_agent)
except:
query_error=(model.sqlclass.error_connection+' '+sys.exc_info()[0], '')
#cursor.close()
return (query_error, False)
c=len(values)
arr_str=['%s' for x in range(c)]
sql="insert into `"+model.name+"` (`"+"`, `".join(fields)+"`) VALUES ("+", ".join(arr_str)+")"
last_sql=sql
cursor=model.query(sql, values, model.connection_id)
if cursor.rowcount>0:
model.last_id=cursor.lastrowid
cursor.close()
# Delete cache for this table.
return (False, True)
else:
query_error=('Cannot insert the new row', last_sql)
return (query_error, False)
class QueryBuilderException(Exception):
pass
def select(model, conditions=['', []], arr_select=[], raw_query=False):
model.clean_fields()
final_fields=[]
extra_fields=[]
#model.query_error=''
query_error=False
last_query=''
#First table selecction
tables_to_select=['`'+model.name+'`']
keys=list(model.fields.keys())
if len(arr_select)==0:
arr_select=keys
# Array intersect for obtain the valid fields
fields = list(set(keys) & set(arr_select))
#Creating the fields
arr_repeat_field={}
new_fields=OrderedDict()
for field in fields:
#Check if foreignkeyfield
if type(model.fields[field]).__name__=="ForeignKeyField" and raw_query==False:
if model.fields[field].table_name in arr_repeat_field:
arr_repeat_field[model.fields[field].table_name]+=1
else:
arr_repeat_field[model.fields[field].table_name]=0
table_name=model.fields[field].table_name+'` as `'+model.fields[field].table_name+str(arr_repeat_field[model.fields[field].table_name])
final_table_name=model.fields[field].table_name+str(arr_repeat_field[model.fields[field].table_name])
# The name with its alias of this related table model
tables_to_select.append('`'+table_name+'`')
# Add field from related table
# as "+table_name+"_"+model.fields[field].named_field
extra_fields.append("`"+final_table_name+"`.`"+model.fields[field].named_field+"` as "+field)
# Add a condition to sql query for join the two tables.
conditions[0]+=" AND `"+final_table_name+"`.`"+model.fields[field].identifier_field+"`=`"+model.name+"`.`"+field+"`"
# Add extra fields from related table from select_fields ForeignKeyField class member
select_fields=model.fields[field].select_fields
for extra_field in select_fields:
model.fields[field+'_'+extra_field]=model.fields[field].related_model.fields[extra_field]
model.fields_to_clean.append(field+'_'+extra_field)
# Check if extra_field is ForeignKeyField, if yes, call this function recursively.
extra_fields.append("`"+final_table_name+"`.`"+extra_field+"` as `"+field+"_"+extra_field+"`")
else:
# Add normal field to sql query
final_fields.append("`"+model.name+"`.`"+field+"`")
#if len(new_fields)>0:
#model.fields.update(new_fields)
extra_sql_field=""
if len(extra_fields)>0:
extra_sql_field=", "+", ".join(extra_fields)
if len(final_fields)==0:
query_error=("Error: without fields to search", '')
#return (query_error, False)
raise QueryBuilderException("Error: without fields to search")
sql= ("select "+" "+model.distinct+", ".join(final_fields)+extra_sql_field+" from "+", ".join(tables_to_select)+' '+conditions[0]).strip()
last_query=sql
cursor=model.query(sql, conditions[1], model.connection_id)
if cursor==False:
#query_error=(model.sqlclass.error_connection, last_query)
#cursor.close()
#return (query_error, False)
raise QueryBuilderException(model.sqlclass.error_connection+last_query)
else:
return cursor
def select_to_array(model, conditions=['', []], fields_selected=[], raw_query=0):
if len(fields_selected)==0:
fields_selected=model.fields.keys()
if (model.name_field_id not in fields_selected):
fields_selected.append(model.name_field_id)
def del_row_id(row):
try:
index_id=row.index(model.name_field_id)
del row[index_id]
except:
pass
else:
def del_row_id(row):
pass
results=[] #OrderedDict()
with select(model, conditions, fields_selected, raw_query) as cursor:
for row in cursor:
if model.show_formatted and row:
for k, col in row.items():
if model.fields[k].show_formatted_value:
row[k]=self.fields[k].show_formatted(col)
results.append(row)
del_row_id(results)
return results
def select_to_dict(model, conditions=['', []], fields_selected=[], raw_query=0, integer_dict=False):
if not integer_dict:
def conv_int(i):
return str(i)
else:
def conv_int(i):
return i
if len(fields_selected)==0:
fields_selected=model.fields.keys()
if (model.name_field_id not in fields_selected):
fields_selected.append(model.name_field_id)
def del_row_id(row):
try:
index_id=row.index(model.name_field_id)
del row[index_id]
except:
pass
else:
def del_row_id(row):
pass
results=OrderedDict()
with select(model, conditions, fields_selected, raw_query) as cursor:
for row in cursor:
if model.show_formatted and row:
for k, col in row.items():
row[k]=model.fields[k].show_formatted(col)
results[conv_int(row[model.name_field_id])]=row
del_row_id(results)
return results
def select_a_row_where(model, conditions=['', []], fields_selected=[], raw_query=0, begin=0):
limit="limit "+str(begin)+", 1"
with select(model, conditions, fields_selected, raw_query) as cursor:
row=cursor.fetchone()
if row==None:
row=False
else:
if model.show_formatted:
for k, col in row.items():
row[k]=model.fields[k].show_formatted(col)
return row
def select_a_row(model, id, fields_selected=[], raw_query=0):
conditions=['WHERE `'+model.name+'`.`'+model.name_field_id+'`=%s', [id]]
with select(model, conditions, fields_selected, raw_query) as cursor:
row=cursor.fetchone()
if row==None:
row=False
else:
if model.show_formatted:
for k, col in row.items():
row[k]=model.fields[k].show_formatted(col)
return row
# A method por count num rows affected for sql conditions
def select_count(model, conditions=['', []], field_to_count='id', raw_query=True):
print(model.dummy)
#First table selecction
tables_to_select=['`'+model.name+'`']
fields=list(model.fields.keys())
#Creating the fields
for field in fields:
#Check if foreignkeyfield
if type(model.fields[field]).__name__=="ForeignKeyField" and raw_query==False:
table_name=model.fields[field].table_name
tables_to_select.append('`'+table_name+'`')
# Add a condition to sql query for join the two tables.
conditions[0]+=" AND `"+table_name+"`.`"+model.fields[field].identifier_field+"`=`"+model.name+"`.`"+field+"`"
sql= "select count(`"+field_to_count+"`) from "+", ".join(tables_to_select)+' '+conditions[0]
count=0
with model.query(sql, conditions[1], model.connection_id) as cursor:
count=list(cursor.fetchone().values())[0]
if model.yes_reset_conditions:
model.reset_conditions()
return count

View file

@ -0,0 +1,44 @@
# A more simple set for make queries
def insert(model, db, dict_values):
final_values={}
for k in model.fields.keys():
final_values[k]=model.fields[k].check(dict_values.get(k, ''))
del final_values[model.name_field_id]
str_fields="`"+"`, `".join(final_values.keys())+"`"
str_query='insert into {} ({}) VALUES ({})'.format(model.name, str_fields, ", ".join(['%s']*len(final_values)))
success=False
with db.query(str_query, list(final_values.values())) as cursor:
if cursor.rowcount>0:
model.last_id=cursor.lastrowid
success=True
return success
def select(model, db, dict_fields=[], where_sql='', limit='', dict_values=[]):
if len(dict_fields)==0:
dict_fields=['`'+field+'`' for field in model.fields.keys()]
str_fields=", ".join(dict_fields)
str_query='select {} from {} {} limit 1'.format(str_fields, model.name, where_sql)
arr_result=[]
with db.query(str_query, dict_values) as cursor:
arr_result=cursor.fetchall()
return arr_result

View file

@ -0,0 +1,164 @@
#!/usr/bin/env python3
from cuchulu.libraries.db.webmodel import WebModel
from cuchulu.libraries.db.coreforms import PasswordForm
from cuchulu.libraries.i18n import I18n
from cuchulu.libraries.httputils import GetPostFiles
class UserModel(WebModel):
"""
Attributes:
password_field (str): The name of the password field to check
email_field (str): The name of the email field to check
username_field (str): The name of the username field to check
yes_repeat_password (bool): If True, check password repeat field, if False, no check repeat password field
check_user (bool): If True, check if user exists in db table, if False, no check that.
check_email (bool): If True, check if email exists in db table, if False, no check that.
"""
def __init__(self, name_field_id="id"):
super().__init__(name_field_id)
self.password_field='password'
self.email_field='email'
self.username_field='username'
self.yes_repeat_password=True
self.check_user=True
self.check_email=True
def create_forms(self, arr_fields=[]):
# Add password_repeat to forms from the model
arr_fields=super().create_forms(arr_fields)
if self.password_field in arr_fields and self.yes_repeat_password:
repeat_password=PasswordForm('repeat_password', '')
repeat_password.required=1
repeat_password.label=I18n.lang('common', 'repeat_password', 'Repeat Password')
repeat_password.field=self.fields['password']
self.create_form_after(self.password_field, repeat_password)
return arr_fields
"""
def insert(self, dict_values, external_agent=True):
if 'password' in dict_values:
dict_values['repeat_password']=dict_values.get('repeat_password', '')
if dict_values['repeat_password']!=dict_values[self.password_field]:
self.fields[self.password_field].error=True
self.fields['password'].txt_error=I18n.lang('common', 'error_passwords_no_match', 'Error: passwords doesn\'t match')
return super().insert(dict_values, external_agent)
"""
def check_all_fields(self, dict_values, external_agent, yes_update=False, errors_set="insert"):
error=0
try:
fields, values, update_values=super().check_all_fields(dict_values, external_agent, yes_update, errors_set)
except:
error+=1
if self.check_user==True:
# Check if passwords matches
if self.password_field in dict_values:
dict_values['repeat_password']=dict_values.get('repeat_password', '')
if dict_values[self.password_field].strip()!="":
if dict_values['repeat_password']!=dict_values[self.password_field]:
self.fields[self.password_field].error=True
self.fields[self.password_field].txt_error=I18n.lang('common', 'error_passwords_no_match', 'Error: passwords doesn\'t match')
error+=1
# Check if exists user with same email or password
get_id=0
if self.updated:
# Need the id
#GetPostFiles.obtain_get()
#GetPostFiles.obtain_post()
getpostfiles=GetPostFiles()
getpostfiles.obtain_get()
get_id=getpostfiles.get.get(self.name_field_id, '0')
post_id=getpostfiles.post.get(self.name_field_id, '0')
if get_id!='0':
get_id=int(get_id)
if post_id!='0':
get_id=int(post_id)
pass
get_id=int(get_id)
sql_id=''
original_conditions=self.conditions
self.reset_conditions()
if self.username_field in dict_values:
self.conditions=['WHERE username=%s AND '+self.name_field_id+'!=%s', [dict_values[self.username_field], get_id]]
if self.select_count()>0:
self.fields[self.username_field].error=True
self.fields[self.username_field].txt_error=I18n.lang('common', 'error_username_exists', 'Error: username already exists')
self.fields_errors[self.username_field].append(self.fields[self.username_field].txt_error)
error+=1
if self.check_email:
if self.email_field in dict_values:
self.conditions=['WHERE email=%s AND '+self.name_field_id+'!=%s', [dict_values[self.email_field], get_id]]
if self.select_count()>0:
self.fields[self.email_field].error=True
self.fields[self.email_field].txt_error=I18n.lang('common', 'error_email_exists', 'Error: this email is already being used')
self.fields_errors[self.email_field].append(self.fields[self.email_field].txt_error)
error+=1
self.conditions=original_conditions
if error>0:
self.query_error+='Error:if is not expected, please, check that you disabled the special checkings of this model'
return False
return fields, values, update_values

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,46 @@
#!/usr/bin/env python3
# A bottle plugin for send emails if error
from settings import config
from cuchulu.libraries.sendmail import SendMail
import sys, traceback
email_failed=''
if hasattr(config, 'email_failed'):
email_failed=config.email_failed
class ErrorReportingPlugin(object):
"""Bottle plugin for """
name = 'error_reporting'
api = 2
def apply(self, callback, context):
def wrapper(*args, **kwargs):
try:
rv = callback(*args, **kwargs)
return rv
except Exception as exception:
#print('detected error')
# Send mail with error.
if email_failed!='' and type(exception).__name__!='HTTPResponse':
sendmail=SendMail()
text=traceback.format_exc()
sendmail.send(email_failed, [email_failed], 'Error reporting from site', text, content_type='plain', attachments=[])
raise
#return rv
return wrapper

View file

@ -0,0 +1,14 @@
#!/usr/bin/env python3
# Code based in http://stackoverflow.com/questions/5194057/better-way-to-convert-file-sizes-in-python
import math
def filesize(size):
if (size == 0):
return '0B'
size_name = ("b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb")
i = int(math.floor(math.log(size,1024)))
p = math.pow(1024,i)
s = round(size/p,2)
return '%s %s' % (s,size_name[i])

View file

@ -0,0 +1,18 @@
#!/usr/bin/env python3
# A simple utility for filter ips. Only use this if you don't use a server with blocking ips system
from settings import config
from bottle import request
def filterip():
#Check ip
ip = request.environ.get('REMOTE_ADDR')
if ip in config.allowed_ips:
return True
else:
return False

View file

@ -0,0 +1,371 @@
"""
Cuchulu2fm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from cuchulu.libraries.lists import SimpleList
from bottle import request
from cuchulu.libraries.urls import add_get_parameters, redirect
from cuchulu.libraries.mtemplates import set_flash_message
from cuchulu.libraries.db.formsutils import show_form
from cuchulu.libraries.i18n import I18n, PGetText
from cuchulu.libraries.httputils import GetPostFiles
from collections import OrderedDict
gtext=PGetText(__file__)
_=gtext.gettext
class GenerateAdminClass:
"""Class for insert, update and list items of a model
"""
def __init__(self, model, url, t):
"""A class for generate forms, insert and update items from a database model
For an easy and fast access to database data, you can use this class for get a simple database model of cuchulu and get list of items, add forms, edit forms and more.
Args:
model (WebModel): A WebModel model (equivalent to database mysql table)
url (str): A string with the base url for the forms.
t (PTemplate): Template used for the class. Normally template subclassed from admin_t PTemplate
Attributes:
model (WebModel): The webmodel used for generate the admin model form
t (PTemplate): Template used for the class. Normally template subclassed from admin_t PTemplate
list (SimpleList): A SimpleList class used for generate the listing
arr_fields_edit (list): A list with the fields that the user can edit
url (str): Base url used by GenerateAdminClass for generate edit, insert and other urls.
template_insert (str): The template used for the insert form
template_admin (str): The template used for the base admin site
template_delete (str): The template used for verify delete of an item
url_redirect (str): The url where user is redirect when an operation is done
post_update (function): A Function with item id used how argument for make a post-progressing after update.
"""
self.model_name=''
self.model=model
self.t=t
self.list=SimpleList(model, url, t)
self.arr_fields_edit=list(model.fields.keys())
del self.arr_fields_edit[self.arr_fields_edit.index(model.name_field_id)]
self.url=url
self.safe=0;
self.arr_links={}
self.hierarchy=None
self.text_add_item=''
self.no_insert=False
self.no_delete=False
self.title=''
self.id=0
self.template_insert='utils/insertform.phtml'
self.template_admin='utils/admin.phtml'
self.template_verify_delete='utils/verify_delete.phtml'
self.url_redirect=self.url
self.pre_update=None
self.post_update=None
self.text_home=_('Home')
def show(self):
""" Method for show the admin model
Depending of op_admin arg, you have the different sections of a simple administrator
Returns:
html (str): The html content of the admin page, can be, items list, forms for create items, etc...
"""
getpostfiles=GetPostFiles()
getpostfiles.obtain_get()
getpostfiles.get['op_admin']=getpostfiles.get.get('op_admin', '0')
getpostfiles.get['id']=getpostfiles.get.get('id', '0')
if len(self.model.forms)==0:
self.model.create_forms()
edit_forms=OrderedDict()
url_action=self.url
for key_form in self.arr_fields_edit:
edit_forms[key_form]=self.model.forms[key_form]
if getpostfiles.get['op_admin']=='1':
post=None
title_edit=_('Add new item')
pass_value=False
if getpostfiles.get['id']!='0':
post=self.model.select_a_row(getpostfiles.get['id'], [], True)
title_edit=_('Edit item')
pass_value=True
if post==None or post==False:
if getpostfiles.get['id']=='0':
post={}
else:
return ""
url_action=add_get_parameters(self.url, op_admin=2, id=getpostfiles.get['id'])
form=show_form(post, edit_forms, self.t, False, pass_value)
return self.t.render_template(self.template_insert, admin=self, title_edit=title_edit, form=form, model=self.model, id=getpostfiles.get['id'], url_action=url_action, enctype=self.model.enctype)
elif getpostfiles.get['op_admin']=='2':
getpostfiles.obtain_post()
#post=getpostfiles.post
self.model.reset_conditions()
insert_row=self.model.insert
try:
getpostfiles.get['id']=str(int(getpostfiles.get['id']))
except:
getpostfiles.get['id']='0'
title_edit=_('Add new item')
if getpostfiles.get['id']!='0':
insert_row=self.model.update
title_edit=_('Edit item')
self.model.conditions=['WHERE `'+self.model.name+'`.`'+self.model.name_field_id+'`=%s', [getpostfiles.get['id']]]
if self.pre_update:
getpostfiles.post=self.pre_update(self, getpostfiles.post)
if insert_row(getpostfiles.post):
set_flash_message(_('Task successful'))
if self.post_update:
if getpostfiles.get['id']=='0':
getpostfiles.get['id']=self.model.insert_id()
self.post_update(self, getpostfiles.get['id'])
redirect(self.url_redirect)
else:
url_action=add_get_parameters(self.url, op_admin=2, id=getpostfiles.get['id'])
form=show_form(getpostfiles.post, edit_forms, self.t, True)
return self.t.render_template(self.template_insert, admin=self, title_edit=title_edit, form=form, model=self.model, id=getpostfiles.get['id'], url_action=url_action, enctype=self.model.enctype)
pass
elif getpostfiles.get['op_admin']=='3':
verified=getpostfiles.get.get('verified', '0')
if verified=='1':
if getpostfiles.get['id']!='0':
self.model.conditions=['WHERE `'+self.model.name+'`.`'+self.model.name_field_id+'`=%s', [getpostfiles.get['id']]]
self.model.delete()
set_flash_message(_('Task successful'))
redirect(self.url_redirect)
else:
return self.t.render_template(self.template_verify_delete, url=self.url, item_id=getpostfiles.get['id'], op_admin=3, verified=1)
else:
return self.t.render_template(self.template_admin, admin=self, add_new_item=_('Add new item'))
"""
def show_config(self):
getpostfiles=GetPostFiles()
getpostfiles.obtain_query()
op=getpostfiles.query.get('op', '')
object_id=getpostfiles.query.get('id', '0')
c=self.model.select_count
if op=='':
# Show the form
return self.t.render_template(self.template_insert, admin=self, title_edit=title_edit, form=form, model=self.model, id=object_id)
"""
class GenerateConfigClass:
"""Class for generate a simple form for simple data for a configuration
"""
def __init__(self, model, url, t):
"""Class for generate a simple form for simple data for a configuration database model
You can use this class if you need a simple table for configurations. You create the model and you can generate the configuration instancing this class in your admin
Args:
model (WebModel): A WebModel model (equivalent to database mysql table)
url (str): A string with the base url for the forms.
t (PTemplate): Template used for the class. Normally template subclassed from admin_t PTemplate
Attributes:
model (WebModel): The webmodel used for generatre the admin model form
t (PTemplate): Template used for the class. Normally template subclassed from admin_t PTemplate
url (str): Base url used by GenerateConfigClass for different sections of update configuration model
url_redirect (str): The url where user is redirect when an operation is done
arr_fields_edit (list): A list with the fields that the user can edit
template_insert (str): The template used for the insert form
post_update (function): A Function with item id used how argument for make a post-progressing after update.
text_home (str): A str contening the text of home configuration
"""
#self.model_name=''
self.model=model
self.title_name=model.label
self.t=t
self.url=url
self.url_redirect=self.url
self.arr_fields_edit=list(model.fields.keys())
del self.arr_fields_edit[self.arr_fields_edit.index(model.name_field_id)]
self.template_insert='utils/insertform.phtml'
self.pre_update=None
self.post_update=None
self.text_home=_('Home')
def show(self):
""" Method for show the config admin model
Depending of op_config arg, you have the different sections of a simple configuration administrator
"""
getpostfiles=GetPostFiles()
getpostfiles.obtain_query()
getpostfiles.query['op_config']=getpostfiles.query.get('op_config', '0')
if len(self.model.forms)==0:
self.model.create_forms()
title_edit=_('Edit')+' '+self.title_name
edit_forms=OrderedDict()
form_values={}
for key_form in self.arr_fields_edit:
edit_forms[key_form]=self.model.forms[key_form]
url_action=add_get_parameters(self.url, op_config=1)
if getpostfiles.query['op_config']=='1':
self.model.yes_reset_conditions=False
getpostfiles.obtain_post()
c=self.model.select_count()
insert_model=self.model.insert
if c:
insert_model=self.model.update
if insert_model(getpostfiles.post):
set_flash_message(_('Task successful'))
self.model.yes_reset_conditions=True
if self.post_update:
self.post_update(self)
redirect(self.url_redirect)
else:
form=show_form(getpostfiles.post, edit_forms, self.t, True)
self.model.yes_reset_conditions=True
return self.t.render_template(self.template_insert, admin=self, title_edit=title_edit, form=form, model=self.model, id='0', url_action=url_action, enctype=self.model.enctype)
else:
form_values=self.model.select_a_row_where([], True)
pass_values=True
if not form_values:
form_values={}
pass_values=False
form=show_form(form_values, edit_forms, self.t, True, pass_values)
return self.t.render_template(self.template_insert, admin=self, title_edit=title_edit, form=form, model=self.model, id=0, url_action=url_action, enctype=self.model.enctype)

View file

@ -0,0 +1,31 @@
#!/usr/bin/env python3
# This module is suitable for create ssl apis that don't need much performance, if you need more performance use nginx or apache proxiying for generate https content and Cuchulu with gunicorn or others wsgi servers for generate the html/json content.
from bottle import ServerAdapter
import ssl
class GunicornServerSSL(ServerAdapter):
""" Untested. See http://gunicorn.org/configure.html for options. """
cert_pem=''
privkey_pem=''
workers=2
def run(self, handler):
from gunicorn.app.base import Application
#'ciphers': 'TLSv1'
#, 'ssl_version': ssl.PROTOCOL_TLSv1
config = {'bind': "%s:%d" % (self.host, int(self.port)), 'workers': self.workers, 'keyfile': self.privkey_pem, 'certfile': self.cert_pem, 'ssl_version': ssl.PROTOCOL_TLSv1}
config.update(self.options)
class GunicornApplication(Application):
def init(self, parser, opts, args):
return config
def load(self):
return handler
GunicornApplication().run()

View file

@ -0,0 +1,144 @@
#/usr/bin/env python3
from cuchulu.libraries.urls import add_get_parameters
class HierarchyLinks:
def __init__(arr_links, t=None):
self.arr_links=arr_links
self.arr_indexes={}
def update_links(self, link_father, link_son, text):
self.arr_links[link_father][link_son]=text
def calculate_indexes():
#oreach(self.arr_links as $father_link => $arr_child_links)
for father_link, arr_child_links in self.arr_links.items():
#foreach($arr_child_links as $link => $text)
for link, text in self.arr_child_links.items():
self.arr_indexes[link]=father_link
def result(last_link, arr_result=[], yes_last_link=0):
self.calculate_indexes()
if last_link in self.arr_indexes:
father=self.arr_indexes[last_link]
arr_last_link[0]=self.no_link
arr_last_link[1]=self.yes_link
yes_link_func=arr_last_link[yes_last_link]
if father!='':
arr_result.append(self.yes_link_func(last_link, self.arr_links[father][last_link]))
yes_last_link=1
arr_result=self.result(father, arr_result, yes_last_link)
return arr_result
else:
arr_result.append(self.yes_link_func(last_link, self.arr_links[father][last_link]))
return arr_result
return arr_result
def show(link, separator='&gt;&gt;', class_link=''):
arr_result=self.result(link)
arr_result=array_reverse(arr_result)
return ' '+separator+' '.join(arr_result)
def yes_link(link, text):
return '<a href="'+link+'">'+text+'</a>'
def no_link(link, text):
return text
class HierarchyModelLinks:
def __init__(self, model, first_element_title, field_name, field_parent, base_url):
self.model=model
self.field_parent=field_parent
self.field_name=field_name
self.base_url=base_url
self.arr_parent={}
self.arr_son=[]
self.first_element_title=first_element_title
def prepare(self):
conditions=self.model.conditions
with self.model.set_conditions('', []).select([self.model.name_field_id, self.field_name, self.field_parent]) as cur:
for arr_model in cur:
if self.field_parent not in self.arr_parent:
self.arr_parent[arr_model[self.model.name_field_id]]=[]
self.arr_parent[arr_model[self.model.name_field_id]]=[arr_model[self.field_name], arr_model[self.field_parent]]
self.model.conditions=conditions
def parents(self, son_id, url_func):
if son_id not in self.arr_parent or son_id==0:
return
self.arr_son.insert(0, url_func(son_id, self.arr_parent[son_id][0]))
self.parents(self.arr_parent[son_id][1], self.url)
def no_url(self, son_id, title):
return title
def url(self, son_id, title):
args={}
args[self.field_parent]=str(son_id)
return '<a href="%s">%s</a>' % (add_get_parameters(self.base_url, **args), title)
def show(self, son_id, separator=' &gt;&gt; '):
try:
son_id=int(son_id)
except:
son_id=0
self.prepare()
self.parents(son_id, self.no_url)
self.arr_son.insert(0, self.url(0, self.first_element_title))
return separator.join(self.arr_son)

View file

@ -0,0 +1,174 @@
#!/usr/bin/env python3
import json, re
from bottle import request, response
from cuchulu.libraries.sessionplugin import get_session
from cuchulu.libraries.keyutils import create_key_encrypt
from bottle import HTTPResponse
no_csrf=False
change_csrf=True
try:
from settings import config
if hasattr(config, 'no_csrf'):
no_csrf=config.no_csrf
if hasattr(config, 'change_csrf'):
change_csrf=config.change_csrf
except:
class config:
no_csrf=False
change_csrf=True
def filter_ajax(data, filter_tags=True):
response.set_header('Content-type', 'application/json')
#arr_data=map(
json_encoded=json.dumps(data)
#if filter_tags:
# json_encoded=json_encoded.replace('<', '&lt;').replace('>', '&gt;')
#json_encoded=re.sub(r'\\"', '&quot;', json_encoded)
#json_encoded=re.sub('\\"', "", json_encoded)
#json_encoded=re.sub('\"', "&quot;", json_encoded)
#replace('\\"', '&quot;')
#replace('\\\\', '${slashes}').
return json_encoded
class GetPostFiles:
# Need this for obtain utf8 valid values
def __init__(self):
# Deprecated. use self.query
self.get={}
self.query={}
self.post={}
self.files={}
def obtain_query(self, ignore_csrf_token=True):
self.query={}
self.query=request.query.decode()
if ignore_csrf_token==False and no_csrf==False:
check_csrf(self.query)
# Deprecated, is confuse.
def obtain_get(self, ignore_csrf_token=True):
self.obtain_query(ignore_csrf_token)
self.get=self.query
def obtain_post(self, required_post=[], ignore_csrf_token=False):
self.post={}
if not request.json:
try:
self.post=request.forms.decode('utf-8')
except:
request.forms.recode_unicode=False
self.post=request.forms.decode('utf-8')
else:
self.post=request.json
#print(self.post.keys())
if len(required_post)==0:
required_post=self.post.keys()
for post in required_post:
self.post[post]=self.post.get(post, '')
s=get_session()
#print('s', s)
if ignore_csrf_token==False and no_csrf==False:
if 'csrf_token' in s:
self.post['csrf_token']=self.post.get('csrf_token', '')
if self.post['csrf_token']!=s['csrf_token'] or self.post['csrf_token'].strip()=="":
# Clean csrf_token
#del s['csrf_token']
#s.save()
#raise NameError('Error: you need a valid csrf_token')
raise HTTPResponse(body=json.dumps({'error_csrf': 1, 'error': 1, 'token_invalid': 1}), status=200, headers={'Content-type': 'application/json'})
else:
#Clean csrf_token
if change_csrf:
del s['csrf_token']
#s.save()
else:
#raise NameError('Error: you don\'t send any valid csrf_token')
raise HTTPResponse(body=json.dumps({'error_csrf': 1, 'error': 1, 'token_invalid': 0}), status=200, headers={'Content-type': 'application/json'})
#Check post_token
def obtain_files(self):
self.files=request.files
def request_method():
return request.method
def check_csrf(post):
s=get_session()
if 'csrf_token' in s:
post['csrf_token']=post.get('csrf_token', '')
if post['csrf_token']!=s['csrf_token'] or post['csrf_token'].strip()=="":
#raise NameError('Error: you need a valid csrf_token')
raise HTTPResponse(body=json.dumps({'error_csrf': 1, 'error': 1, 'token_invalid': 1}), status=200, headers={'Content-type': 'application/json'})
else:
#Clean csrf_token
if change_csrf:
del s['csrf_token']
#s.save()
else:
#raise NameError('Error: you don\'t send any valid csrf_token')
raise HTTPResponse(body=json.dumps({'error_csrf': 1, 'error': 1, 'message': 'Error: csrf token invalid', 'token_invalid': 0}), status=200, headers={'Content-type': 'application/json'})

246
cuchulu/libraries/i18n.py Normal file
View file

@ -0,0 +1,246 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for bottle.py, mako and others and construct a simple headless cms.
Copyright (C) 2024 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from importlib import import_module
from cuchulu.libraries.sessionplugin import get_session
import json
from bottle import request
import gettext
import os
yes_session=False
i18n_module={}
def load_lang(*args):
"""A function for load the lang module dinamically
"""
for module in args:
lang_path=module[0]+'.i18n.'+module[1]
try:
i18n_module[lang_path]=import_module(lang_path)
pass
except:
pass
# here load the language
class PGetText:
# Dict where all gettext domain are saved -> domain=name, example, admin, libraries, pastafari2, etc...
l={}
def __init__(self, module_file):
module_dir=os.path.dirname(os.path.realpath(module_file))
module_name=os.path.basename(module_dir)
if module_name not in PGetText.l:
PGetText.l[module_name]={}
for i in I18n.dict_i18n:
if i not in PGetText.l[module_name]:
PGetText.l[module_name][i]=gettext.translation(module_name, module_dir+'/languages/', languages=[i], fallback=True)
PGetText.l[module_name][i].install()
self.module=module_name
def gettext(self, text):
return PGetText.l[self.module][I18n.get_default_lang()].gettext(text)
def pgettext(module_file):
module=os.path.dirname(os.path.realpath(module_file))
base_name=os.path.dirname(os.path.realpath(module))
l=gettext.translation(os.path.basename(base_name), module+'/languages/', languages=I18n.get_default_lang(), fallback=True)
return l.gettext
class I18n:
"""Class for i18n tasks
Class for i18n tasks, how, strings for every language supported, for now are en-US and es-ES. You can add more languages adding
Attributes:
default_lang (str): The default string lang used when get someone
dict_i18n (list): The list with default languages. You can add more calling it static variable in settings/config.py
"""
default_lang='en-US'
dict_i18n=['en-US', 'es-ES']
l={}
def __init__(self, module):
self.module=module
def clang(self, module, symbol, text_default):
"""Static method for get a string from selected language
Static method used to get the string of the selected language. If there is no string in the selected language, it returns text_default.
Args:
module (str): The module to which the translation string belongs
symbol (str): Simple symbol that is useful for identify the string
text_default (str): The text used by default when there are not translation in the selected language
"""
#if not lang:
# lang=I18n.get_default_lang()
lang=self.default_lang
I18n.l[lang]=I18n.l.get(lang, {})
I18n.l[lang][module]=I18n.l[lang].get(module, {})
I18n.l[lang][module][symbol]=I18n.l[lang][module].get(symbol, text_default)
return I18n.l[lang][module][symbol]
def slang(self, symbol, text_default, lang=None):
"""Method for get a string from selected language but object oriented
Method for get a string from selected language but object oriented
Args:
symbol (str): The symbol used for identify the text string.
text_default (str): The text default used. You have use how base for translations.
"""
return I18n.lang(self.module, symbol, text_default, lang)
def tlang(self, text_default, lang=None):
"""Method for get a string from selected language but object oriented and using module and symbol by default
Method for get a string from selected language but object oriented and using module and symbol by default
Args:
symbol (str): The symbol used for identify the text string.
text_default (str): The text default used. You have use how base for translations.
"""
symbol=text_default[:60]
return I18n.lang(self.module, symbol, text_default, lang)
@staticmethod
def add_lang(lang, module, symbol, text):
I18n.l[lang]=I18n.l.get(lang, {})
I18n.l[lang][module]=I18n.l[lang].get(module, {})
I18n.l[lang][module][symbol]=text
#@staticmethod
#def set_lang(code_lang):
# if default_lang
@staticmethod
def get_default_lang():
"""Static method for get the default lang"""
lang=I18n.default_lang
s=get_session()
lang=s.get('lang', lang)
return lang
@staticmethod
def lang(module, symbol, text_default, lang=None):
"""Static method for get a string from selected language
Static method used to get the string of the selected language. If there is no string in the selected language, it returns text_default.
Args:
module (str): The module to which the translation string belongs
symbol (str): Simple symbol that is useful for identify the string
text_default (str): The text used by default when there are not translation in the selected language
"""
if not lang:
lang=I18n.get_default_lang()
I18n.l[lang]=I18n.l.get(lang, {})
I18n.l[lang][module]=I18n.l[lang].get(module, {})
I18n.l[lang][module][symbol]=I18n.l[lang][module].get(symbol, text_default)
return I18n.l[lang][module][symbol]
@staticmethod
def extract_value(value):
"""Static method for get values from json lang array
Args:
value (json): Lang dict in json format
"""
value=json.loads(value)
lang=I18n.get_default_lang()
if value[lang]!='':
return value[lang]
return value[I18n.default_lang]
@staticmethod
def get_browser_lang():
"""Method for get the language from user browser"""
return request.headers.get('Accept-Language', 'en-US')
@staticmethod
def lang_json(module, symbol, text_default):
arr_final={}
for l in I18n.dict_i18n:
arr_final[l]=I18n.lang(module, symbol, text_default, l)
return json.dumps(arr_final)
common_pgettext=PGetText(__file__)

12
cuchulu/libraries/js.py Normal file
View file

@ -0,0 +1,12 @@
from cuchulu.libraries.sessionplugin import get_session
from cuchulu.libraries.i18n import I18n
from settings import config
def make_js_url(file_path, module):
#/mediajs/<module>/<lang>/<filename:path>
s=get_session()
lang=I18n.get_default_lang()
return config.base_url+'mediajs/%s/%s/%s' % (module, lang, file_path)

View file

@ -0,0 +1,86 @@
"""
Cuchulufm is a series of wrappers for bottlepy, mako and others and construct a simple headless cms.
Copyright (C) 2024 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from hashlib import sha512, sha256
from base64 import b64encode
from os import urandom
import string
import secrets
# Functions for create random strings usando urandom
def create_key_encrypt(n=10):
""" Simple function for create a random string
Simple function for create a random string based in sha512
Args:
n (int): size of string random bytes (view urandom function in Python3 Help)
"""
return sha512(urandom(n)).hexdigest()
def create_key_encrypt_256(n=10):
""" Simple function for create a random string
Simple function for create a random string based in sha256
Args:
n (int): size of string random bytes (view urandom function in Python3 Help)
"""
return sha256(urandom(n)).hexdigest()
def create_key(n=10):
""" Simple function for create a random string
Simple function for create a random string based in urandom function and base64 encoding
Args:
n (int): size of string random bytes (view urandom function in Python3 Help)
"""
rand_bytes=urandom(n)
return b64encode(rand_bytes).decode('utf-8')[0:-2]
def create_simple_password(n=14):
""" Based in python3 documentation for create passwords using secrets module
https://docs.python.org/3/library/secrets.html
Args:
n (int): Number of random elements of the password
"""
password=''
alphabet=string.ascii_letters+string.digits+string.punctuation
while True:
password=''.join(secrets.choice(alphabet) for i in range(n))
if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3):
break
return password

View file

@ -0,0 +1,61 @@
# Translations for libraries
# Copyright (C) 2025
# This file is distributed under the same license as the Paramecio package.
# Antonio de la Rosa <antonio.delarosa@salirdelhoyo.com>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-03-21 18:11+0100\n"
"PO-Revision-Date: 2025-03-21 18:15+0100\n"
"Last-Translator: \n"
"Language-Team: \n"
"Language: en_US\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 3.5\n"
#: templates/utils/list.phtml:25
msgid "Search"
msgstr "Search"
#: templates/utils/list.phtml:144 lists.py:317
msgid "Pages"
msgstr "Pages"
#: lists.py:83
msgid "Options"
msgstr "Options"
#: lists.py:174 generate_admin_class.py:239
msgid "Edit"
msgstr "Edit"
#: lists.py:175
msgid "Delete"
msgstr "Delete"
#: pages.py:71
msgid "Last"
msgstr "Last"
#: generate_admin_class.py:60 generate_admin_class.py:225
msgid "Home"
msgstr "Home"
#: generate_admin_class.py:87 generate_admin_class.py:127
#: generate_admin_class.py:173
msgid "Add new item"
msgstr "Add new item"
#: generate_admin_class.py:93 generate_admin_class.py:132
msgid "Edit item"
msgstr "Edit item"
#: generate_admin_class.py:139 generate_admin_class.py:165
#: generate_admin_class.py:264
msgid "Task successful"
msgstr "Task successful"

View file

@ -0,0 +1,61 @@
# Translations for libraries
# Copyright (C) 2025
# This file is distributed under the same license as the Paramecio package.
# Antonio de la Rosa <antonio.delarosa@salirdelhoyo.com>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-03-21 18:11+0100\n"
"PO-Revision-Date: 2025-03-21 18:15+0100\n"
"Last-Translator: \n"
"Language-Team: \n"
"Language: es_ES\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 3.5\n"
#: templates/utils/list.phtml:25
msgid "Search"
msgstr "Buscar"
#: templates/utils/list.phtml:144 lists.py:317
msgid "Pages"
msgstr "Páginas"
#: lists.py:83
msgid "Options"
msgstr "Opciones"
#: lists.py:174 generate_admin_class.py:239
msgid "Edit"
msgstr "Editar"
#: lists.py:175
msgid "Delete"
msgstr "Borrar"
#: pages.py:71
msgid "Last"
msgstr "Último"
#: generate_admin_class.py:60 generate_admin_class.py:225
msgid "Home"
msgstr "Inicio"
#: generate_admin_class.py:87 generate_admin_class.py:127
#: generate_admin_class.py:173
msgid "Add new item"
msgstr "Añadir nuevo elemento"
#: generate_admin_class.py:93 generate_admin_class.py:132
msgid "Edit item"
msgstr "Editar elemento"
#: generate_admin_class.py:139 generate_admin_class.py:165
#: generate_admin_class.py:264
msgid "Task successful"
msgstr "Tarea exitosa"

View file

@ -0,0 +1,60 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-03-21 18:11+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"
#: templates/utils/list.phtml:25
msgid "Search"
msgstr ""
#: templates/utils/list.phtml:144 lists.py:317
msgid "Pages"
msgstr ""
#: lists.py:83
msgid "Options"
msgstr ""
#: lists.py:174 generate_admin_class.py:239
msgid "Edit"
msgstr ""
#: lists.py:175
msgid "Delete"
msgstr ""
#: pages.py:71
msgid "Last"
msgstr ""
#: generate_admin_class.py:60 generate_admin_class.py:225
msgid "Home"
msgstr ""
#: generate_admin_class.py:87 generate_admin_class.py:127
#: generate_admin_class.py:173
msgid "Add new item"
msgstr ""
#: generate_admin_class.py:93 generate_admin_class.py:132
msgid "Edit item"
msgstr ""
#: generate_admin_class.py:139 generate_admin_class.py:165
#: generate_admin_class.py:264
msgid "Task successful"
msgstr ""

450
cuchulu/libraries/lists.py Normal file
View file

@ -0,0 +1,450 @@
"""
Cuchulu2fm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
#By default id is not showed
from cuchulu.libraries.pages import Pages
from cuchulu.libraries.urls import add_get_parameters
from cuchulu.libraries.sessions import get_session
from cuchulu.libraries.i18n import I18n, PGetText
from cuchulu.libraries.httputils import GetPostFiles
from bottle import request
import sys
import re
from cuchulu.libraries.pages import Pages
gtext=PGetText(__file__)
_=gtext.gettext
class SimpleList:
"""Class for create item list from a model table
"""
def __init__(self, model, url, t):
"""Class for create item list from a model table
You can create lists using a WebModel. You can select the show fields, and you have features how order by field and simple searchs.
Args:
model (WebModel): A WebModel model (equivalent to database mysql table)
url (str): A string with the base url for the forms.
t (PTemplate): Template used for the class. Normally template subclassed from admin_t PTemplate
Attributes:
raw_query (boolean): If True then raw query is done, if False then query with all related fields is done
t (PTemplate): Template used for the class. Normally template subclassed from admin_t PTemplate
model (WebModel): The webmodel used for generate the admin model form
fields (list): A list with fields names of model getting of db query
fields_showed (list): A list with fields names of model showed in list
url (str): Base url used by SimpleList for generate edit, insert and other urls.
limit_pages (int): The number of items by page. By default, 20 items
order_defaults (list): Internal list used for define Ascendent and Descendent in sql queries
order_class (list): Internal list used for show icons for ascendent or descendent field selection
order (str): Default order used in order_defaults list
order_field (str): The default field used for order the list. By default is the model id field
order_by (str): The default order ASC or DESC defined in order_class list. By default is 0 or ASC
change_order (dict): Internal dict used for get all ordenable fields from model
yes_search (boolean): If True, a search form is showed, if False, the search form is hidden.
search_text (str): Used for save the search text sended via POST.
initial_num_pages (int): Initial number of pages showed in pagination.
table_div (boolean): If True, use div for create the table, if False, use standard html table for create the table.
begin_page (int): Number that is used for begin the elements to get from query
search_fields (list): The fields used for search data in form.
arr_extra_fields (list): List with the names of extra fields
arr_extra_options (list): List with a set of functions used how extra fields. This functions return lists with different options, joined with jln attribute.
jln (list): Jump line for join options by default.
ajax (boolean): If True, ajax is used for get items for the list and change page, if False, typical httpd request is used for change the items page.
"""
self.raw_query=True
self.getpostfiles=GetPostFiles()
self.getpostfiles.obtain_get()
self.t=t
self.model=model
#if len(self.model.forms)==0:
#self.model.create_forms()
self.fields=model.fields.keys()
self.fields_showed=self.fields
self.url=url
self.limit_pages=20
self.order_defaults=['ASC', 'DESC']
self.order_class=['down', 'up']
self.s=get_session()
#clean session
self.order='0'
self.order_field=self.model.name_field_id
self.order_by=self.order_defaults[0]
self.change_order={}
self.yes_search=True
self.search_text=''
self.initial_num_pages=20
self.table_div=False
request.query.get('begin_page', '0')
try:
self.begin_page=int(request.query.begin_page)
except ValueError:
self.begin_page=0
if self.begin_page<0:
self.begin_page=0
self.search_fields=self.fields
#self.yes_options=True
self.arr_extra_fields=[_('Options')]
self.arr_extra_options=[SimpleList.standard_options]
self.jln='<br />'
self.ajax=False
def restore_fields(self):
"""Simple method for restore default fields from model
"""
self.fields=self.model.fields.keys()
def obtain_order(self):
"""Function for set the order query defaults for list from http request query args.
"""
self.order=self.getpostfiles.get.get('order', self.order)
order_k=int(self.order)
#Obtain from get
"""
if 'order' in request.query.keys():
"""
#order_k=int(request.query.get('order', 0))
if order_k>1 or order_k<0:
order_k=0
self.order_by=self.order_defaults[ order_k ]
self.order=order_k
def obtain_field_search(self):
"""Function for set the field search query defaults for list from http request query args.
"""
self.order_field=self.getpostfiles.get.get('order_field', self.order_field)
field_k=self.order_field
"""
if 'order_field' in request.query.keys():
field_k=request.query.order_field
"""
if field_k in self.model.fields.keys():
self.order_field=field_k
for field in self.fields:
#Initialize foreignkeyfield fields too
if type(self.model.fields[field]).__name__=='ForeignKeyField':
name_related=self.model.fields[field].related_model.name
for k in self.model.fields[field].related_model.fields.keys():
self.change_order[field+'_'+k]=self.order
self.change_order[field]=self.order
if self.order==0:
self.change_order[field_k]=1
else:
self.change_order[field_k]=0
#self.order_field=self.order_field
def search(self):
"""Function for set the text order query defaults for list from http request query args.
"""
self.getpostfiles.get['search_text']=self.getpostfiles.get.get('search_text', '')
self.search_text=self.getpostfiles.get['search_text']
self.search_text=self.search_text.replace('"', '&quot;')
#self.model.conditions='AND
self.search_field=self.getpostfiles.get.get('search_field', '')
if self.search_field not in self.model.fields.keys():
self.search_field=''
if self.search_field!='' and self.search_text!='':
self.model.conditions[0]+=' AND '+self.search_field+' LIKE %s'
self.model.conditions[1].append('%'+self.search_text+'%')
pass
def set_options(self, options_func, arr_row):
"""Method for join options list returns with jln attributte separator
Returns:
options (str): Return a string with joined options
"""
return self.jln.join(options_func(self.url, arr_row[self.model.name_field_id], arr_row))
@staticmethod
def standard_options(url, id, arr_row):
"""Static method for get standar options for make things with the items row.
Returns:
options (list): Return a list of basic options for items row
"""
options=[]
options.append('<a href="'+add_get_parameters(url, op_admin=1, id=id)+'">'+_('Edit')+'</a>')
options.append('<a href="'+add_get_parameters(url, op_admin=3, id=id)+'">'+_('Delete')+'</a>')
return options
def show(self):
"""Method for show the table
The principal method of the class. The list is showed with the selected fields, search form, pagination...
"""
self.model.yes_reset_conditions=False
self.obtain_order()
self.obtain_field_search()
self.search()
total_elements=self.model.select_count()
num_elements=self.limit_pages
link=add_get_parameters(self.url, search_text=self.search_text, search_field=self.search_field, order=self.order)
begin_page=self.begin_page
self.model.order_by='order by '+self.order_field+' '+self.order_by
if self.limit_pages>0:
self.model.limit='limit '+str(begin_page)+','+str(self.limit_pages)
list_items=self.model.select(self.fields, self.raw_query)
#print(self.model.fields.keys())
func_jscript=''
if self.ajax==True:
func_jscript='get_page()'
pages=''
if self.limit_pages>0:
pages=Pages.show( begin_page, total_elements, num_elements, link ,initial_num_pages=self.initial_num_pages, variable='begin_page', label='', func_jscript='')
self.begin_page=str(self.begin_page)
self.model.yes_reset_conditions=True
listing=self.t.render_template('utils/list.phtml', simplelist=self, list=list_items, pages=pages, ajax=self.ajax)
list_items.close()
return listing
"""
@staticmethod
def get_ajax_page(model):
p=GetPostFiles()
p.obtain_query()
pass
"""
class AjaxList(SimpleList):
"""Class for make a list from a table based in Ajax
"""
# Fields example: [['Hostname', True], ['IP', True], ['Options', False]]
# arr_order_fields=['server.hostname', 'server.ip']
# 'select count(servercloud.id) as num_elements from servercloud where servercloud.user_id=%s'
# params count_query [s['cu_id']]
# str_query no order, no limit -> select server.hostname, server.ip, servercloud.id from server, servercloud where server.id=servercloud.server_id and servercloud.user_id=%s
# str_query_params -> [s['cu_id'], begin_page, limit]
def __init__(self, db, fields, arr_order_fields, count_query, str_query):
"""Class for make a list from a table based in Ajax
A class that is useful for creating listings based on database models using Ajax
Args:
db (sql connection): A MySQL connection used for get the model.
fields (list): A list with the fields showed in table
arr_order_fields (list): A list with the sql names of selected fields for show.
count_query (str): sql segment for count query sentence. Example: select count(id) from table WHERE name=%s
str_query (str): sql segment for query sentence. Example: select id from table WHERE name=%s
Attributes:
fields (list): A list with the fields showed in table
arr_order_fields (list): A list with the sql names of selected fields for show.
limit (int): the number of items selected in query sentence.
count_query (str): sql segment for count query sentence. Example: select count(id) from table WHERE name=%s
count_query_params (list): A list with the params for parse a sql count query with %s symbols (View python help about sql sentences and connectors)
str_query (str): sql segment for query sentence. Example: select id from table WHERE name=%s
str_query_params (list): A list with the params for parse a sql query with %s symbols (View python help about sql sentences and connectors)
initial_num_pages (int): Initial number of pages showed in pagination.
db (sql connection): A MySQL connection used for get the model.
func_fields (dict): A series of functions used for a series of extra fields referring to each row of the table
initial_order_field (str): FIeld used for order the table in first execution
initial_order (int): If 0, the initial order is Ascendent, if 1, the initial order is Descendent.
"""
self.fields=fields
self.arr_order_fields=arr_order_fields
self.limit=20
self.count_query=count_query[0]
self.count_query_params=count_query[1]
self.str_query=str_query[0]
self.str_query_params=str_query[1]
self.initial_num_pages=20
self.db=db
self.func_fields={}
self.initial_order_field=''
self.initial_order=0
def show(self):
"""Method for show the table
The principal method of the class. The list is showed with the selected fields, search form, pagination...
"""
begin_page=int(request.query.get('position', 0))
order_field=request.query.get('order_field', self.initial_order_field)
order=request.query.get('order', self.initial_order)
limit=self.limit
arr_order=['ASC', 'DESC']
order_sql=''
order_params=[]
if order_field!='':
try:
order_field=int(order_field)
order=int(order)
if order_field>=0 and order_field<len(self.arr_order_fields):
order_sql='order by %s' % self.arr_order_fields[order_field]
if order>=0 and order<2:
order_sql+=' %s' % arr_order[order]
#order_params=[self.arr_order_fields[order_field]]
except:
order_field=0
order=0
rows=[]
with self.db.query(self.count_query, self.count_query_params) as cursor:
total_elements=cursor.fetchone()['num_elements']
str_query=self.str_query+' '+order_sql
params=self.str_query_params
html_pages=''
if self.limit>0:
str_query+=' limit %s, %s'
params.append(begin_page)
params.append(limit)
pages=Pages()
html_pages=_('Pages')+': '+pages.show( begin_page, total_elements, limit, '#' ,initial_num_pages=self.initial_num_pages, variable='begin_page', label='', func_jscript='')
with self.db.query(str_query, params) as cursor:
for row in cursor:
"""
c=len(self.arr_order_fields)
for x in range(c, len(row)):
key_field=list(row.keys())[x]
#print(key_field)
pass
"""
for func_field in self.func_fields:
if func_field in row:
row[func_field]=self.func_fields[func_field](row[func_field], row)
rows.append(row)
#{k:d[k] for in set(d).intersection(l)}
return {'fields': self.fields, 'rows': rows, 'html_pages': html_pages}
class SimpleAjaxList():
pass

View file

@ -0,0 +1,479 @@
#!/usr/bin/python
"""
Cuchulufm is a series of wrappers for Bottle.py, mako and others and construct a simple headless cms.
Copyright (C) 2024 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from bottle import hook
from mako.template import Template
from mako.lookup import TemplateLookup
from cuchulu.libraries.urls import make_url, make_url_domain, make_media_url, make_media_url_module, add_get_parameters
from cuchulu.libraries.i18n import I18n, PGetText
from cuchulu.libraries.sessionplugin import get_session
from cuchulu.libraries.adminutils import make_admin_url
from cuchulu.libraries.db.formsutils import csrf_token
from cuchulu.libraries.js import make_js_url
from settings import config
from os import path
from collections import OrderedDict
from cuchulu.wsgiapp import app
gtext=PGetText(__file__)
_=gtext.gettext
# Preparing envs for views of modules, and views of
def env_theme(module, cache_enabled=True, cache_impl='', cache_args={}, module_directory="./tmp/modules"):
"""Function for create an environment for mako templates
Function for create an environment for mako templates. Really is a shortcut for TemplateLookup mako function. You can define cache options and module_directory for templates compiled
Args:
module (str): The module where the templates can be founded
cache_enabled (boolean): If True then mako template cache is enabled, is False, mako template cache is disabled.
cache_args (dict): Cache Args dict parameter for TemplateLookup function from Mako templates. View Mako Templates documentation.
module_directory (str): Module directory parameter for TemplateLookup function from Mako templates. View Mako Templates documentation.
Returns:
template (TemplateLookup): Return TemplateLookup object
"""
ext=module[len(module)-3:]
if ext=='.py':
module=path.dirname(module)
standard_templates=path.dirname(__file__)+'/templates'
module_directory+='/'+module
module_templates=module+'/templates'
theme_templates='themes/'+config.theme+'/templates'
search_folders=[theme_templates, module_templates, standard_templates]
#if self.inject_folder is not None:
#search_folders.insert(1, self.inject_folder+'/templates')
#Standard templates
#print(standard_templates)
return TemplateLookup(directories=search_folders, default_filters=['h'], input_encoding='utf-8', encoding_errors='replace', cache_enabled=cache_enabled, cache_impl=cache_impl, cache_args=cache_args, module_directory=module_directory, filesystem_checks=config.reloader)
def preload_templates(template_files, env):
templates={}
for template_file in template_files:
templates[template_file]=env.get_template(template_file)
return templates
def url_for(name, **kwargs):
return app.get_url(name, **kwargs)
def get_file():
return __file__
class PTemplate:
"""A class used how shortcuts for Mako template functions.
"""
templates_loaded={}
def __init__(self, environment):
"""A class used how shortcuts for Mako template functions.
This class is used to have a set of shortcuts and hooks to Mako templates functions and methods over a series of default options.
Args:
environment (TemplateLookup): A TemplateLookup object generated with env_theme function
Attributes:
autoescape_ext (set): A set of extensions file where automatic autoescape is used
environment (TemplateLookup): A TemplateLookup object generated with env_theme function
filters (list): A list of functions used for add filters to your templates.
js (list): A list of javascript sources for generate js html load tags.
"""
# A simple method used in internal things of cuchulu
self.show_basic_template=True
"""
ext=module[len(module)-3:]
if ext=='.py':
module=path.dirname(module)
"""
self.autoescape_ext=('html', 'htm', 'xml', 'phtml', 'js')
"""
self.cache_enabled=cache_enabled
self.cache_impl=cache_impl
self.cache_args=cache_args
self.module_directory="./tmp/modules"
"""
self.inject_folder=None
self.filters={}
#Place where templates contexts is loaded
self.templates={}
#Adding basic filters for urls
self.add_filter(make_url)
self.add_filter(make_url_domain)
self.add_filter(make_media_url)
self.add_filter(make_media_url_module)
self.add_filter(add_get_parameters)
self.add_filter(csrf_token)
self.add_filter(make_admin_url)
self.add_filter(make_js_url)
I18n_lang=I18n.lang
self.add_filter(I18n.lang)
self.add_filter(I18n.get_default_lang)
self.headerhtml=HeaderHTML()
self.add_filter(self.headerhtml.add_css_home)
self.add_filter(self.headerhtml.add_js_home)
self.add_filter(self.headerhtml.add_css_home_local)
self.add_filter(self.headerhtml.add_js_home_local)
self.add_filter(self.headerhtml.add_header_home)
self.add_filter(qf)
self.filters['HeaderHTML']=self.headerhtml
self.filters['show_flash_message']=self.headerhtml.show_flash_message
self.env=environment
# Loading language domain for gettext in templates
base_name=path.dirname(path.realpath(__file__))
module_env=self.env.directories[1].replace('/templates', '')
self.l=PGetText(module_env+'/app.py')
self.add_filter(self._)
self.i18n=I18n(base_name)
self.add_filter(self.i18n.slang)
self.add_filter(self.i18n.tlang)
#self.url_for=lambda name: app.get_url(name)
#x = lambda a : a + 10
#print(self.url_for)
self.add_filter(url_for)
self.add_filter(get_file)
def _(self, text):
return self.l.gettext(text)
#self.auto_reload=True
# Clean HeaderHTML
"""
HeaderHTML.css=[]
HeaderHTML.js=[]
HeaderHTML.header=[]
HeaderHTML.cache_header=[]
HeaderHTML.css_local={}
HeaderHTML.js_local={}
"""
def guess_autoescape(self, template_name):
"""Simple helper method for get an extension from filename
Args:
template_name (str): The template name
"""
if template_name is None or '.' not in template_name:
return False
ext = template_name.rsplit('.', 1)[1]
return ext in self.autoescape_ext
"""
def env_theme(self, module):
standard_templates=path.dirname(__file__)+'/templates'
module_templates=module+'/templates'
theme_templates='themes/'+config.theme+'/templates'
search_folders=[theme_templates, module_templates, standard_templates]
#if self.inject_folder is not None:
#search_folders.insert(1, self.inject_folder+'/templates')
#Standard templates
#print(standard_templates)
return TemplateLookup(directories=search_folders, default_filters=['h'], input_encoding='utf-8', encoding_errors='replace', cache_enabled=self.cache_enabled, cache_impl=self.cache_impl, cache_args=self.cache_args, module_directory=self.module_directory)
#, cache_enabled=self.cache_enabled, cache_impl=self.cache_impl, cache_args=self.cache_args
#return Environment(autoescape=self.guess_autoescape, auto_reload=True, loader=FileSystemLoader([theme_templates, module_templates]))
"""
def load_templates(self, template_files):
for template_file in template_files:
self.templates[template_file]=self.env.get_template(template_file)
def load_template(self, template_file, **arguments):
"""Load a mako template and return the result
Load a mako template and return the results with different arguments applied
Args:
template_file (str): The name of template file. The template is searched using configuration defined in self.env
**arguments (mixed): Extra arguments with variables passed to template
Returns:
template (str): Return a template rendered using mako class from self.env
"""
template = self.env.get_template(template_file)
arguments.update(self.filters)
#arguments['make_media_url']=make_media_url
return template.render(**arguments)
def render_template(self, template_file, **arguments):
"""Experimental method for parse a template
Experimental method for parse a template, similar to load_template but try cache the template loaded
Args:
template_file (str): The name of template file. The template is searched using configuration defined in self.env
**arguments (mixed): Extra arguments with variables passed to template
Returns:
dummy (str): Dummy return necessary because mako expect return something
"""
if not str(self.env.directories)+'/'+template_file in PTemplate.templates_loaded:
PTemplate.templates_loaded[str(self.env.directories)+'/'+template_file]=self.env.get_template(template_file)
arguments.update(self.filters)
return PTemplate.templates_loaded[str(self.env.directories)+'/'+template_file].render(**arguments)
def add_filter(self, filter_name):
self.filters[filter_name.__name__]=filter_name
class STemplate:
def __init__(html_code):
return Template(html_code)
# DEPRECATED, use utilities from mako for personalize headers.
class HeaderHTML:
def __init__(self):
self.css=[]
self.js=[]
self.header=[]
self.cache_header=OrderedDict()
self.css_local=OrderedDict()
self.js_local=OrderedDict()
def header_home(self):
final_header="\n".join(self.header)
self.header=[]
return final_header
def js_home(self):
final_js=[]
for js in self.js:
final_js.append('<script language="Javascript" src="'+make_media_url('js/'+js)+'"></script>')
for module, arr_js in self.js_local.items():
for js in arr_js:
final_js.append('<script language="Javascript" src="'+make_media_url_module('js/'+js, module)+'"></script>')
self.js=[]
self.js_local=OrderedDict()
return "\n".join(final_js)
def css_home(self):
final_css=[]
for css in self.css:
final_css.append('<link href="'+make_media_url('css/'+css)+'" rel="stylesheet" type="text/css"/>')
for module, arr_css in self.css_local.items():
for css in arr_css:
final_css.append('<link href="'+make_media_url_module('css/'+css, module)+'" rel="stylesheet" type="text/css"/>')
self.css=[]
self.css_local=OrderedDict()
return "\n".join(final_css)
def add_header_home(self, variable, only_one_time=False):
if only_one_time==True:
self.cache_header.get(variable, 0)
if cache_header[variable]==1:
return ''
#self.cache_header[variable]=1
self.header.append(variable)
return ''
def add_css_home(self, css):
if not css in self.css:
self.css.append(css)
return ''
def add_js_home(self, js):
if not js in self.js:
self.js.append(js)
return ''
def add_css_home_local(self, css, module):
if not css in self.css_local:
self.css_local[module]=self.css_local.get(module, [])
try:
self.css_local[module].index(css)
except:
self.css_local[module].append(css)
return ''
def add_js_home_local(self, js, module):
if not js in self.js_local:
self.js_local[module]=self.js_local.get(module, [])
try:
self.js_local[module].index(js)
except:
self.js_local[module].append(js)
return ''
def show_flash_message(self):
message=""
s=get_session()
s['flash']=s.get('flash', "")
if s['flash']!="":
message='<div class="flash">'+s['flash']+'</div><script>setTimeout(function () { $(".flash").fadeOut(); }, 3000);</script>'
s['flash']=''
#s.save()
return message
def set_flash_message(message):
s=get_session()
s['flash']=message
s.save()
def qf(text):
return text.replace('"', '\\"')
env=env_theme(__file__)
standard_t=PTemplate(env)

111
cuchulu/libraries/pages.py Normal file
View file

@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""
Cuchulu2fm is a series of wrappers for bottle, mako and others and construct a simple headless cms.
Copyright (C) 2025 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from math import ceil, floor
from cuchulu.libraries.urls import add_get_parameters
from cuchulu.libraries.i18n import I18n, PGetText
gtext=PGetText(__file__)
_=gtext.gettext
class Pages:
"""Simple class for create html pagination code"""
css_class='link_pages'
@staticmethod
def show( begin_page, total_elements, num_elements, link ,initial_num_pages=20, variable='begin_page', label='', func_jscript=''):
"""Static method for create the html pagination
With this method, you can create html pagination code with automated urls for load every page. You can use it also how base for ajax pagination
Args:
begin_page (int): The number where pagination begin
total_elements (int): The total items in pages
num_elements (int): The number of items for every page
link (str): The url of every page
initial_num_pages (int): Optional. Number of pages showed in pagination, if you have 50 pages, if this value is 20, an interval of 20 pages is showed, with first pages links, and after pages links for navigate between many pages.
variable (str): Optional. The name of GET url variable used for send the first element in the query for get the page.
label (str): Optional. In the future will be used for identify some html tags
func_jscript (str): Javascript function to be executed when page url is clicked.
"""
pages='';
if begin_page>total_elements:
begin_page=0
# Calculamos el total de todas las páginas
total_page=ceil(total_elements/num_elements)
# Calculamos en que página nos encontramos
actual_page=ceil(begin_page/num_elements)
# Calculamos el total de intervalos
total_interval=ceil(total_page/initial_num_pages)
# Calculamos el intervalo en el que estamos
actual_interval=floor(actual_page/initial_num_pages)
# Calculamos el elemento de inicio del intervalo
initial_page=ceil(actual_interval*initial_num_pages*num_elements)
last_page=ceil(actual_interval*initial_num_pages*num_elements)+ceil(initial_num_pages*num_elements)
if last_page>total_elements:
last_page=total_elements
if initial_page>0:
initial_link=add_get_parameters(link, **{variable: '0'});
middle_link=add_get_parameters(link, **{variable: str((initial_page-num_elements)) } );
pages += "<a class=\""+Pages.css_class+"\" href=\""+initial_link+"\" onclick=\"${func_jscript}\">1</a> <a class=\""+Pages.css_class+"\" href=\""+middle_link+"\">&lt;&lt;</a> "
arr_pages={}
#for(x=initial_page;x<last_page;x+=num_elements)
for x in range(initial_page, last_page, num_elements):
middle_link=add_get_parameters(link, **{variable: str(x)} )
num_page=ceil(x/num_elements)+1;
arr_pages[x]="<a class=\""+Pages.css_class+"\" href=\""+middle_link+"\">"+str(num_page)+"</a> "
arr_pages[begin_page]='<span class="selected_page">'+str(num_page)+'</span> ';
pages += arr_pages[x]
if last_page<total_elements:
middle_link=add_get_parameters(link, **{variable: str(x+num_elements)} );
last_link=add_get_parameters(link, **{variable: str( ( ( total_page*num_elements ) - num_elements) ) } )
pages += "<a class=\""+Pages.css_class+"\" href=\""+middle_link+"\" onclick=\"func_jscript\">&gt;&gt;</a> <a class=\"link_pages\" href=\""+last_link+"\" onclick=\"func_jscript\">"+_('Last')+"</a>"
return pages

View file

@ -0,0 +1,163 @@
from cuchulu.modules.admin.models.admin import UserAdmin
from bottle import request
from cuchulu.libraries.sessions import get_session
from cuchulu.libraries.urls import redirect, make_url
from cuchulu.libraries.db.webmodel import WebModel
import inspect
class LoginPlugin(object):
"""Plugin for simple login"""
name = 'login'
api = 2
def __init__(self, keyword='login', login_var='login', login_url='login'):
"""Simple bottle plugin for standard login
Args:
keyword (str): The variable name for activate the plugin
login_var (str): The name used for define the login variable
login_url (str): The url of the login page
"""
self.keyword=keyword
self.login_var=login_var
self.login_url=login_url
def setup(self, app):
"""Make sure that other installed plugins don't affect the same keyword argument.
Args:
app (Bottle): The app object used in the request.
"""
for other in app.plugins:
if not isinstance(other, LoginPlugin): continue
if other.keyword == self.keyword:
raise PluginError("Found another login plugin with "\
"conflicting settings (non-unique keyword).")
def apply(self, callback, context):
"""Test if the original callback accepts a 'login' keyword.
Ignore it if it does not need a login handle.
Args:
callback (function): The callback used in the plugin
context (object): An object with the context of function
Returns:
function: return the result of the route
"""
conf = context.config.get(self.keyword) or {}
keyword = conf.get('keyword', self.keyword)
args = inspect.getfullargspec(context.callback)[0]
if keyword not in args:
return callback
def wrapper(*args, **kwargs):
s=get_session()
if self.login_var in s:
rv = callback(*args, **kwargs)
return rv
else:
#Check if remember_login cookie
#, secret=config.key_encrypt
redirect(make_url(self.login_url))
# Replace the route callback with the wrapped one.
return wrapper
class AdminLoginPlugin(LoginPlugin):
"""A plugin for admin things. DEPRECATED"""
name = 'adminlogin'
api = 2
def __init__(self, keyword='login_admin'):
self.keyword=keyword
class DbPlugin(object):
"""A Bottle plugin for create a connection to database"""
name = 'db'
api = 2
def __init__(self, keyword='db'):
"""A Bottle plugin for create a connection to database"""
self.keyword=keyword
def setup(self, app):
''' Make sure that other installed plugins don't affect the same keyword argument.'''
for other in app.plugins:
if not isinstance(other, DbPlugin): continue
if other.keyword == self.keyword:
raise PluginError("Found another login plugin with "\
"conflicting settings (non-unique keyword).")
def apply(self, callback, context):
"""Test if the original callback accepts a 'db' keyword.
Ignore it if it does not need a login handle.
Args:
callback (function): The callback used in the plugin
context (object): An object with the context of function
Returns:
function: return the result of the route
"""
conf = context.config.get('db') or {}
keyword = conf.get('keyword', self.keyword)
args = inspect.getfullargspec(context.callback)[0]
if keyword not in args:
return callback
def wrapper(*args, **kwargs):
kwargs['db']=WebModel.connection()
try:
rv = callback(*args, **kwargs)
except:
kwargs['db'].close()
raise
kwargs['db'].close()
return rv
return wrapper

View file

@ -0,0 +1,47 @@
from cuchulu.libraries.db import corefields
from cuchulu.libraries.db.extrafields.jsonfield import JsonField
from cuchulu.libraries.db.extrafields.dictfield import DictField
try:
import ujson as json
except:
import json
"""A class for list objects with data fields
"""
class ListItem:
pass
"""Typical item """
class Items(ListItem):
name=corefields.CharField('name')
class StandardResponse:
error=corefields.BooleanField('error')
message=corefields.CharField('message')
code_error=corefields.IntegerField('code_error')
error_form=DictField('error_form', corefields.CharField('error_form'))
#items=JsonField('items', corefields.CharField)
def __init__(self, error=0, message='', code_error=0):
self.error=error
self.message=message
self.code_error=code_error
def toDict(self):
return self.__dict__
def toJSON(self):
return json.dumps( self, default=lambda o: o.__dict__, sort_keys=True, indent=4 )
class ResponseItems(StandardResponse):
pass

View file

@ -0,0 +1,250 @@
#!/usr/bin/env python3
"""
Cuchulufm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import os
import smtplib
import mimetypes
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr, formatdate
import ssl as ssl_module
import sys
class SendMail:
"""Class for send email
"""
port=587
host='localhost'
username=''
password=''
#ssl=True
def __init__(self, ssl=True):
"""Class for send email
Class for send email using standard python library
Attributes:
port (int): The port used for send email, by default 587
host (str): The hostname of mail server used for send the email
username (str): The username for login in mail server
password (str): The password for login in mail server
smtp (smtplib.SMTP): The python SMTP object used for send emails
txt_error: (str): If error, is saved in this attribute
"""
self.smtp=None #smtplib.SMTP(host=self.host, port=self.port)
self.txt_error=''
self.ssl=ssl
if sys.version_info < (3, 6):
self.context = ssl_module.SSLContext(ssl_module.PROTOCOL_TLSv1_2)
else:
self.context = ssl_module.SSLContext(ssl_module.PROTOCOL_TLS)
def connect(self):
self.smtp=smtplib.SMTP(host=self.host, port=self.port)
if self.ssl==True:
try:
self.smtp.starttls(context=self.context)
except smtplib.SMTPHeloError:
self.txt_error='Error: cannot make HELO to this server'
return False
except RuntimeError:
self.txt_error='Error: SSL/TLS is not supported in your python interpreter'
return False
except smtplib.SMTPException as e:
self.txt_error=e.__str__()
return False
#login
if self.smtp!=None:
try:
self.smtp.login(self.username, self.password)
except smtplib.SMTPHeloError:
self.txt_error='Error: cannot make HELO to this server'
return False
except smtplib.SMTPAuthenticationError as eauth:
self.txt_error='Error: cannot login. Wrong username or password '+eauth.__str__()
return False
except smtplib.SMTPException as e:
# self.txt_error=e.__str__()
self.txt_error='Error: any method for login is avaliable - '+e.__str__()
return False
return True
def send(self, from_address, to_address: list, subject, message, content_type='plain', attachments=[], reply_to=()):
""" Method for send email
With this method you can send email to multiple address, html, and add attachments to email
Args:
from_address (str): The adress used for send the email
to_address (list): A list of emails where the email will be sended.
subject (str): The subject of the email
message (str): The content of the message
content_type (str): The type of mail content, can be plain or html.
attachments (list): A list with a serie of file paths for attach to the email.
"""
if self.smtp==None:
if not self.connect():
return False
if len(reply_to)==0:
reply_to=(from_address, from_address)
COMMASPACE=', '
if len(attachments)==0:
msg=MIMEText(message, content_type)
msg['Subject']=subject
msg['Reply-To']=formataddr(reply_to)
msg['From']=from_address
msg['To']=COMMASPACE.join(to_address)
self.smtp.send_message(msg)
#self.quit()
return True
else:
outer=MIMEMultipart()
outer['Subject']=subject
msg['Reply-To']=formataddr(reply_to)
outer['From']=from_address
outer['To']=COMMASPACE.join(to_address)
#outer['Date']=formatdate()
#Attach message text
msg=MIMEText(message, content_type)
outer.attach(msg)
for path in attachments:
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
#No guess could be made, or the file is encoded (compressed), so
#use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
if maintype == 'text':
with open(path) as fp:
# Note: we should handle calculating the charset
msg = MIMEText(fp.read(), _subtype=subtype)
elif maintype == 'image':
with open(path, 'rb') as fp:
msg = MIMEImage(fp.read(), _subtype=subtype)
elif maintype == 'audio':
with open(path, 'rb') as fp:
msg = MIMEAudio(fp.read(), _subtype=subtype)
else:
with open(path, 'rb') as fp:
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
#Encode the payload using Base64
encoders.encode_base64(msg)
#Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path))
outer.attach(msg)
self.smtp.send_message(outer)
#self.quit()
return True
def quit(self):
"""Function used when you need quit connection for any reason"""
if self.smtp!=None:
self.smtp.quit()
self.smtp=None
def __del__(self):
"""Method for clean the connection when the object is closed"""
if self.smtp!=None:
self.smtp.quit()

View file

@ -0,0 +1,205 @@
from bottle import request, response
from itsdangerous.url_safe import URLSafeTimedSerializer
from cuchulu.libraries.keyutils import create_key_encrypt, create_key_encrypt_256, create_key
try:
from settings import config
except:
class config:
cookie_name='cuchulu.session'
key_encrypt=create_key_encrypt_256(30)
session_opts={'session.data_dir': 'sessions', 'session.type': 'file', 'session.path': 'cuchulu'}
import inspect
class Session(dict):
"""Class for create sessions using itsdangerous library"""
def __init__(self, *args, **kwargs):
"""Class for create sessions using itsdangerous library"""
self.update(*args, **kwargs)
self.changed=False
self.safe=None
def __setitem__(self, item, value):
"""Method for set items in session
With this method, session instance set changed property for know that the session was changed and saved
Args:
item (str): The key of the session item
value (mixed): The value of the session item
"""
super(Session, self).__setitem__(item, value)
self.changed=True
# If use redirect or abort, you can save the session before of redirection
def save(self):
"""Method for save the session
When bottle make a redirect, directly make a raise exception and not save session. With this method you can save the session before the raise.
"""
if self.changed:
if not self.safe:
self.safe=URLSafeTimedSerializer(config.key_encrypt)
#if not max_age:
response.set_cookie(config.cookie_name, self.safe.dumps(self), path=config.session_opts['session.path'], httponly=True)
"""
def __del__(self):
self.save()
print('exit')
"""
def get_session():
"""Function for get the session from request object from bottle"""
return request.environ.get('session', Session())
def session_plugin(callback):
def wrapper(*args, **kwargs):
cookie=request.get_cookie(config.cookie_name)
safe=None
if not cookie:
session=Session()
else:
safe=URLSafeTimedSerializer(config.key_encrypt)
try:
session=Session(safe.loads(cookie))
if type(session).__name__!='Session':
session=Session()
session.safe=safe
except:
session=Session()
if 'session' in kwargs:
kwargs['session']=session
#For compatibility with old sessions server-side style.
request.environ['session']=session
rv=callback(*args, **kwargs)
if session.changed:
#print('changed')
if not safe:
safe=URLSafeTimedSerializer(config.key_encrypt)
#if not max_age:
response.set_cookie(config.cookie_name, safe.dumps(session), path=config.session_opts['session.path'], httponly=True)
return rv
return wrapper
class SessionPlugin(object):
name = 'session'
api = 2
def __init__(self, keyword='session'):
self.keyword=keyword
self.session=None
def setup(self, app):
''' Make sure that other installed plugins don't affect the same keyword argument.'''
for other in app.plugins:
if not isinstance(other, SessionPlugin): continue
if other.keyword == self.keyword:
raise PluginError("Found another login plugin with "\
"conflicting settings (non-unique keyword).")
def apply(self, callback, context):
# Test if the original callback accepts a 'session' keyword.
# Ignore it if it does not need a login handle.
conf = context.config.get('session') or {}
keyword = conf.get('keyword', self.keyword)
args = inspect.getfullargspec(context.callback)[0]
"""
if keyword not in args:
return callback
"""
if keyword in args:
#print(args[keyword])
self.session=True
def wrapper(*args, **kwargs):
cookie=request.get_cookie(config.cookie_name)
safe=None
if not cookie:
session=Session()
else:
safe=URLSafeTimedSerializer(config.key_encrypt)
try:
session=Session(safe.loads(cookie))
if type(session).__name__!='Session':
session=Session()
except:
session=Session()
#if 'session' in kwargs:
#print(kwargs)
if self.session:
kwargs['session']=session
#For compatibility with old sessions server-side style.
request.environ['session']=session
rv=callback(*args, **kwargs)
if session.changed:
#print('changed')
if not safe:
safe=URLSafeTimedSerializer(config.key_encrypt)
#if not max_age:
response.set_cookie(config.cookie_name, safe.dumps(session), path=config.session_opts['session.path'], httponly=True)
return rv
return wrapper

View file

@ -0,0 +1,288 @@
#!/usr/bin/env python3
from cuchulu.libraries.keyutils import create_key_encrypt, create_key_encrypt_256, create_key
#from oslo_concurrency import lockutils
try:
from settings import config
except:
class config:
cookie_name='cuchulu.session'
key_encrypt=create_key_encrypt_256(30)
session_opts={'session.data_dir': 'sessions', 'session.type': 'file', 'session.path': 'cuchulu'}
#from itsdangerous import JSONWebSignatureSerializer
from bottle import request, response
import os
try:
import ujson as json
except:
import json
import fcntl
import errno
import time
import shutil
import uuid
#from diskcache import Cache
#from dogpile.cache import make_region
# Cookie session
# This save the session in a cookie for maximum performance. In next version i can use memcached or something for session
# In next versions have two secret_keys for more security.
class CuchuluSession:
def __init__(self, session_dict):
self.session=session_dict
def get(self, name, default_value):
if not name in self.session:
self.session[name]=default_value
return self.session[name]
def __getitem__(self, key):
return self.session[key]
def __setitem__(self, key, value):
self.session[key]=value
def __delitem__(self, key):
if key!='token':
del self.session[key]
def __contains__(self, key):
if key in self.session:
return True
else:
return False
def __iter__(self):
return self.session
def __str__(self):
return self.session.__str__()
def keys(self):
return self.session.keys()
def remove(self):
response.delete_cookie(config.cookie_name, path="/")
def delete(self):
self.remove()
def save(self):
# Here get the function for load session
save_session(self.session['token'], self.session)
def reset(self):
token=self.session['token']
self.session={'token': token}
self.save()
def get_session(max_age=None):
s={}
try:
if request.environ:
if not 'session' in request.environ:
cookie=None
if request.cookies.get(config.cookie_name):
cookie=request.get_cookie(config.cookie_name)
if not cookie:
if hasattr(request, 'app'):
s=generate_session({}, max_age)
else:
# Here get the function for load session
s=load_session(cookie)
request.environ['session']=s
else:
s=request.environ['session']
except RuntimeError:
pass
return CuchuluSession(s)
if config.session_opts['session.type']=='mysql':
pass
elif config.session_opts['session.type']=='redis':
import redis
def generate_session(session={}, max_age=None):
token=create_key(30).replace('/', '#')
s={'token': token}
# Bug in python 3.6, if you put max_age how None, is passed to header cookie.
if not max_age:
response.set_cookie(config.cookie_name, token, path=config.session_opts['session.path'], httponly=True)
else:
response.set_cookie(config.cookie_name, token, path=config.session_opts['session.path'], max_age=max_age, httponly=True)
request.environ['session']=s
save_session(token, s)
request.environ['session']=s
return s
def regenerate_session():
token=create_key(30).replace('/', '#')
s={'token': token}
response.set_cookie(config.cookie_name, token, path=config.session_opts['session.path'], httponly=True)
save_session(token, s)
request.environ['session']=s
return CuchuluSession(s)
def load_session(token):
s={}
r=redis.Redis(host=config.session_opts['session.host'], port=config.session_opts['session.port'], decode_responses=True)
value=r.get(token)
r.close()
if not value:
s={'token': token}
else:
try:
s=json.loads(value)
except:
s={'token': token}
return s
def save_session(token, session):
r=redis.Redis(host=config.session_opts['session.host'], port=config.session_opts['session.port'])
r.set(token, json.dumps(session))
r.close()
def after_session():
pass
else:
def generate_session(session={}, max_age=None):
token=create_key(30).replace('/', '#')
s={'token': token}
# Bug in python 3.6, if you put max_age how None, is passed to header cookie.
if not max_age:
response.set_cookie(config.cookie_name, token, path=config.session_opts['session.path'], httponly=True)
else:
response.set_cookie(config.cookie_name, token, path=config.session_opts['session.path'], max_age=max_age, httponly=True)
#Set-Cookie: phango_session=n2ro4lghim75p8vjseb5v3lhap; path=/experiment2/
#response.set_header('Set-Cookie', '%s=%s; path=%s' % (config.cookie_name, token, config.session_opts['session.path']) )
request.environ['session']=s
file_session=config.session_opts['session.data_dir']+'/'+token+'_session'
save_session(token, s, True)
request.environ['session']=s
return s
def regenerate_session():
token=create_key(30).replace('/', '#')
s={'token': token}
response.set_cookie(config.cookie_name, token, path=config.session_opts['session.path'], httponly=True)
file_session=config.session_opts['session.data_dir']+'/'+token+'_session'
save_session(token, s, True)
request.environ['session']=s
return CuchuluSession(s)
def load_session(token):
file_session=config.session_opts['session.data_dir']+'/'+token+'_session'
if os.path.isfile(file_session):
with open(file_session) as f:
try:
s=json.loads(f.read())
os.utime(file_session)
except:
s={'token': token}
else:
return generate_session({'token': token})
return s
#@lockutils.synchronized('not_thread_safe')
def save_session(token, session, create_file=False):
file_session=config.session_opts['session.data_dir']+'/'+token+'_session'
# Check if exists lock
if os.path.isfile(file_session) or create_file:
with open(file_session, 'w') as f:
#try:
json_session=json.dumps(session)
f.write(json_session)

View file

@ -0,0 +1,18 @@
#!/usr/bin/env python3
def show_links(switch, arr_links):
final_links=[]
for link in arr_links:
if link[0]==switch:
final_links.append(link[1])
break
else:
final_links.append('<a href="'+link[2]+'">'+link[1]+'</a>')
return final_links

View file

@ -0,0 +1,30 @@
"""
Cuchulu2fm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from slugify import slugify as slugify_func
def slugify(slug, *args, **wargs):
"""Simple wrapper for slugify module https://github.com/un33k/python-slugify
Args:
slug (str): The string to be slugified
"""
return slugify_func(slug, *args, **wargs)

View file

@ -0,0 +1,179 @@
#!/usr/bin/python
from jinja2 import Template, Environment, FileSystemLoader
from cuchulu.libraries.urls import make_url, make_media_url, make_media_url_module, add_get_parameters
from cuchulu.libraries.i18n import I18n
from cuchulu.libraries.sessions import get_session
from settings import config
# Preparing envs for views of modules, and views of
""" A simple function for load views from themes using jinja2
Env use loader = FileSystemLoader(['/path/to/templates', '/other/path'])
env = Environment(loader=FileSystemLoader(['/path/to/templates', '/other/path']))
template = env.get_template('mytemplate.html')
"""
class ptemplate:
def __init__(self, module):
self.autoescape_ext=('html', 'htm', 'xml', 'phtml')
self.env=self.env_theme(module)
#Adding basic filters for urls
self.add_filter(make_url)
self.add_filter(make_media_url)
self.add_filter(make_media_url_module)
self.add_filter(add_get_parameters)
I18n_lang=I18n.lang
self.add_filter(I18n.lang)
self.add_filter(add_css_home)
self.add_filter(add_js_home)
self.add_filter(add_header_home)
self.auto_reload=True
# Clean HeaderHTML
HeaderHTML.css=[]
HeaderHTML.js=[]
HeaderHTML.header=[]
HeaderHTML.cache_header=[]
def guess_autoescape(self, template_name):
if template_name is None or '.' not in template_name:
return False
ext = template_name.rsplit('.', 1)[1]
return ext in self.autoescape_ext
def env_theme(self, module):
#standard_templates=path.dirname(__file__)+'/templates'
module_templates=module+'/templates'
theme_templates='themes/'+config.theme+'/templates'
return Environment(autoescape=self.guess_autoescape, auto_reload=True, loader=FileSystemLoader([theme_templates, module_templates]))
def load_template(self, template_file, **arguments):
template = self.env.get_template(template_file)
arguments['HeaderHTML']=HeaderHTML
arguments['show_flash_message']=show_flash_message
#Will be nice add hooks here
return template.render(arguments)
def add_filter(self, filter_name):
self.env.filters[filter_name.__name__]=filter_name
class HeaderHTML:
css=[]
js=[]
header=[]
cache_header={}
def header_home():
final_header="\n".join(HeaderHTML.header)
HeaderHTML.header=[]
return final_header
def js_home():
final_js=[]
for js in HeaderHTML.js:
final_js.append('<script language="Javascript" src="'+make_media_url('js/'+js)+'"></script>')
HeaderHTML.js=[]
return "\n".join(final_js)
def css_home():
final_css=[]
for css in HeaderHTML.css:
final_css.append('<link href="'+make_media_url('css/'+css)+'" rel="stylesheet" type="text/css"/>')
HeaderHTML.css=[]
return "\n".join(final_css)
def add_header_home(variable, only_one_time=False):
if only_one_time==True:
HeaderHTML.cache_header.get(variable, 0)
if cache_header[variable]==1:
return ''
#HeaderHTML.cache_header[variable]=1
HeaderHTML.header.append(variable)
return ''
def add_css_home(css):
if not css in HeaderHTML.css:
HeaderHTML.css.append(css)
return ""
def add_js_home(js):
if not js in HeaderHTML.js:
HeaderHTML.js.append(js)
return ""
def set_flash_message(message):
s=get_session()
s['flash']=s.get('flash', "")
s['flash']=message
def show_flash_message():
message=""
s=get_session()
s['flash']=s.get('flash', "")
if s['flash']!="":
message='<div class="flash">'+s['flash']+'</div>'
s['flash']=''
return message
standard_t=ptemplate(__file__)

Some files were not shown because too many files have changed in this diff Show more