Full Chapter Designing Microservices With Django An Overview of Tools and Practices 1St Edition Akos Hochrein PDF

You might also like

You are on page 1of 53

Designing Microservices with Django

An Overview of Tools and Practices 1st


Edition Akos Hochrein
Visit to download the full and correct content document:
https://textbookfull.com/product/designing-microservices-with-django-an-overview-of-t
ools-and-practices-1st-edition-akos-hochrein/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Django Design Patterns and Best Practices 2nd Edition


Arun Ravindran

https://textbookfull.com/product/django-design-patterns-and-best-
practices-2nd-edition-arun-ravindran/

Django For Beginners: Build Websites With Python And


Django William S. Vincent

https://textbookfull.com/product/django-for-beginners-build-
websites-with-python-and-django-william-s-vincent/

Tango With Django: A beginner’s Guide to Web


Development With Python / Django 1.9 1st Edition Leif
Azzopardi

https://textbookfull.com/product/tango-with-django-a-beginners-
guide-to-web-development-with-python-django-1-9-1st-edition-leif-
azzopardi/

Django for Professionals Production Websites with


Python Django William S. Vincent

https://textbookfull.com/product/django-for-professionals-
production-websites-with-python-django-william-s-vincent/
Tango With Django 2 1st Edition Leif Azzopardi

https://textbookfull.com/product/tango-with-django-2-1st-edition-
leif-azzopardi/

Pro Spring Boot 2: An Authoritative Guide to Building


Microservices, Web and Enterprise Applications, and
Best Practices 2nd Edition Felipe Gutierrez

https://textbookfull.com/product/pro-spring-boot-2-an-
authoritative-guide-to-building-microservices-web-and-enterprise-
applications-and-best-practices-2nd-edition-felipe-gutierrez/

Pro Spring Boot 2 An Authoritative Guide to Building


Microservices Web and Enterprise Applications and Best
Practices Second Edition Felipe Gutierrez

https://textbookfull.com/product/pro-spring-boot-2-an-
authoritative-guide-to-building-microservices-web-and-enterprise-
applications-and-best-practices-second-edition-felipe-gutierrez/

Traefik API Gateway for Microservices: With Java and


Python Microservices Deployed in Kubernetes 1st Edition
Rahul Sharma

https://textbookfull.com/product/traefik-api-gateway-for-
microservices-with-java-and-python-microservices-deployed-in-
kubernetes-1st-edition-rahul-sharma/

Practical Tools for Designing and Weighting Survey


Samples Richard Valliant

https://textbookfull.com/product/practical-tools-for-designing-
and-weighting-survey-samples-richard-valliant/
Akos Hochrein

Designing Microservices with Django


An Overview of Tools and Practices
Akos Hochrein
Berlin, Germany

Any source code or other supplementary material referenced by the


author in this book is available to readers on GitHub via the book’s
product page, located at www.​apress.​com/​978-1-4842-5357-1 . For
more detailed information, please visit http://​www.​apress.​com/​
source-code .

ISBN 978-1-4842-5357-1 e-ISBN 978-1-4842-5358-8


https://doi.org/10.1007/978-1-4842-5358-8

© Akos Hochrein 2019

Apress Standard

Trademarked names, logos, and images may appear in this book. Rather
than use a trademark symbol with every occurrence of a trademarked
name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark. The use in this publication
of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of
opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true
and accurate at the date of publication, neither the authors nor the
editors nor the publisher can accept any legal responsibility for any
errors or omissions that may be made. The publisher makes no
warranty, express or implied, with respect to the material contained
herein.

Distributed to the book trade worldwide by Springer Science+Business


Media New York, 233 Spring Street, 6th Floor, New York, NY 10013.
Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-
ny@springer-sbm.com, or visit www.springeronline.com. Apress Media,
LLC is a California LLC and the sole member (owner) is Springer
Science + Business Media Finance Inc (SSBM Finance Inc). SSBM
Finance Inc is a Delaware corporation.
For my aunts
Introduction
Welcome toDesigning Microservices with Django . I decided to grab a
pen and write this book because it was quite difficult for me to find
easily digestible guides on how to design microservices, including some
of the problems I might face along the way and the potential solutions
to them.
I kick off this book by clarifying some of the terminology regarding
service design. Together, we look at a couple of anecdotes that will help
us understand the benefits and drawbacks of certain systems.
After that, we dive into Django development and develop an
application for ourselves that we talk about later in the book. We
examine various high-level concepts such as templates and view
functions, in addition to lower level ones, such as permissions and user
management.
Now armed with knowledge of Django development, we delve
deeply into the different types of microservices and the high-level
design principles we should follow when we design them. We also take
a look at communication principles, such as REST (from the
synchronous world) and AMQP (from the asynchronous world), to
achieve an understanding of how these protocols work and which ones
solve which sorts of problems.
Armed with microservice design knowledge, we study the
methodologies and techniques of migrating code into smaller systems.
To close, we look at how we can scale our development by making
tools that make microservices possible to all developers in a company. I
hope you are excited about this journey. I certainly am; so let’s get
started!
Acknowledgments
Writing down thoughts and creating a book is quite a difficult endeavor,
and it requires a lot of people and luck to get it done. Luckily, I’ve had
both on my side.
This is the place where I thank the entire Django community for
being there and developing the basis of this book. Thank you! Stay
awesome!
A thank you is in order to the publisher for helping me along the
way and making sure I kept progressing even when I felt like no
progress was being made. Thank you.
A big thank you is in order for the technical reviewers, Balá zs and
Csaba. They kept me focused and gave me great feedback on the
direction and the contents of the book. They also aided me throughout
my career to get to this point, for which I will always be grateful. Thank
you! You are truly my friends.
I thank my friends here in Berlin and back in Budapest who kept me
sane and pushed me through all the creative blocks I had throughout
the writing process, even when I needed you to pay for the beer. Thank
you. You know who you are.
Thanks need to go to my family as well, who encouraged me to
follow my dreams and pushed me through difficult times in my life.
Thanks Mom, Dad, and Zalá n. I’m lucky to have you in my life.
Table of Contents
Chapter 1:​What are services?​
Service Lingo
Software as a Service
Service-oriented Architecture
Monolithic Service
Microservice
Understanding the Monolith
Understanding the Microservice
Early Design Choices
Summary
Chapter 2:​A Pinch of Django
Introducing the Problem
Getting Started
Django Apps
Models and the Power of ORMs
What are ORMs?​
The Pizza
Migrations
Simple ORM Examples
Communication with Views
The Admin Panel
Logging in, Logging Out and Signing up
Signing up
Login and Logout
A Primer on Middlewares
Templates
Permissions
Conclusion
Chapter 3:​Anatomy of a Microservice
Backend Services
A Note on Data Duplication
Front-end Services
Mixed Services
Design Principles
SOLID Building Blocks
12 factors
Conclusion
Chapter 4:​Communication
REST and the Synchronous World
What is REST
HTTP Verbs, the Way REST Talks
Response Codes, What REST Really Means When it’s Talking
The Django REST Framework
Asynchronous Communication
Concept of the Queue
Example Solution - RabbitMQ
Asynchronous Best Practices
Conclusion
Chapter 5:​From Monolith to Microservice
Before you Start
Human Costs
Infrastructure Costs
I Made the Call, What’s Next?​
Data Preparation
Domain Sharding
Database Duplication
Testing and Coverage
Moving the Service
Remote Models
The Code Migration
Release
Cleanup
Conclusion
Chapter 6:​Scaling Development
Using Python Packages
What to Reuse
Creating a New Package
Testing Packages
Service Repositories
Designing a Service Repository
Looking for Data
Other Useful Tields
Scaffolding
Scaffolding the Codebase
Scaffolding the Infrastructure
Conclusion
Index
About the Author and About the Technical
Reviewers

About the Author


Akos Hochrein
is a software engineer and technical lead.
After receiving his degree in computer
science, he started his career as a
consultant and soon became a product
developer at a well-known Hungarian
startup, later moving to Berlin to dive
into the local tech scene and to broaden
his back-end architecture design
experience. Throughout his career, he
worked in areas such as front-end and
back-end development, integrations,
data streaming, and systems design.
Occasionally, he shares his knowledge in
various forums, such as technical conferences, his blog, . . . or a book.

About the Technical Reviewers


Balázs Tóthfalussy
is a technical lead and software engineer, and former mentor of the
author. After studying financial software development, he committed to
the sector and expanded his knowledge as a Java developer. Later, he
moved to China to extend his knowledge in agile development
practices. There, he fell in love with Python, which he has been working
with ever since. Today he leads a team of developers to deliver tooling
to create a more pleasant experience for dozens of engineers at his
company.
© Akos Hochrein 2019
A. Hochrein, Designing Microservices with Django
https://doi.org/10.1007/978-1-4842-5358-8_1

1. What are services?


Akos Hochrein1

(1) Berlin, Germany

Services have been around humanity since before the agricultural


revolution. Whenever we go into a store or a restaurant, we are using a
service. Some services are more complex than others and provide
goods to us that are more tailored to our taste or require less effort to
work with, whereas some of them are more specialized, focusing on a
single task and doing that really well. Let’s take a look at a simple
example.
Both a market and a restaurant qualify as services, and even though,
they provide us with different things, both of them give us the general
item of food. When you enter a market, you can buy various ingredients
from various sellers. Later on, you can combine all of these ingredients
into various dishes of your liking at home. A fancy restaurant, however,
will provide you with delicacies made on the spot. There are many
processes and systems working in the backend of a restaurant, most of
it you have no sense of, but after your request if processed, you get your
meal delivered.
The restaurant/market-stall analogy is just one of many that we can
bring up when we are talking about services. Conceptually, they work
the same way as services in software.
1. You, the client, approach the service with a request.

2. The service, in our case the restaurant, receives your order.


3. Some algorithms and processes in the background (the recipes and
the chefs) prepare a response for you.

4. You receive the aforementioned response (most of the cases, at


least).

A service could be your application that serves people on their


phone information on the number of times they left their home
yesterday. Or a service could be a massive continuous integration
system that you only see a small portion of that runs your application’s
tests. A service could also be something tiny in software, an application
that provides an interface to get information about what time it is in
Budapest, Hungary.
In this book, we are going to focus on services that reside on the
web, serving data to the end users and to other, internal services alike.
Let’s begin by taking a look at the different definitions that emerged in
the industry.

Service Lingo
In the past couple of years, there has been a lot of buzz around service
design, software as a service, microservices, monoliths, service-
oriented architecture, and so on. In the next figure, it is plain to see that
microservices are becoming more and more popular. Figure 1-1
provides a graphical view of Google searches of “microservices” over
the past five years.
Figure 1-1 Popularity of the term “microservices” since 2014, Google
In the following sections we will try to make some sense on what
each of these mean and what are the important terms you need to
remember when you are working in systems like these. Please keep in
mind that these terms are not etched into stone.

Software as a Service
The term “software as a service ” (or SaaS) mostly describes a licensing
model, where you can pay for the usage of some sort of online service.
Most of these software live in the cloud and provide various ways for
the end user to modify and query data in their systems. One example
here is Spotify, an online music streaming software, which end users
can use to listen to music and create their own playlist. Furthermore,
Spotify has an extensive software interface and packages which
engineers can use to fetch and modify data in the Spotify cloud
programmatically.
Service-oriented Architecture
Service oriented architecture (or SoA) is probably one of the favourite
terms in the industry. In simple terms, this style of architecture design
supports services more than anything. A service, as we learned above,
needs to serve some sort of business need and needs to be modeled
around real world requirements. Services need to be self contained and
have a clean interface with which they can be communicated with. They
are deployed and developed independently and represent a unit of
functionality on an abstract level. The architecture also involves the
communication protocols used between these services. Some software
as a service companies use service-oriented architecture to deliver
quality products to their end users.

Monolithic Service
One of the dreaded words of the decade for software engineers.
Monolithic applications and monolithic services are single services that
grew too big to be able to reason about. What “too big” means exactly
will be one of the core topics of this book. We will also see that this
dreaded word does not necessarily mean something bad.

Microservice
The other dreaded word of the decade for software engineers
(although, for different reasons). A microservice, in short, is a service
that lives in a service-oriented architecture and is easy to reason about.
These are loosely coupled, lightweight components which have a well
defined interface, a single-purpose and are easy to create and dispose
of. Due to the fine-grained nature, more people can work on them in
parallel and ownership of features becomes a cleaner problem to solve
for the organization.
Now that we’ve taken a look at the high level definitions, let’s do a
deep dive into monoliths.

Understanding the Monolith


As we’ve learned, monoliths are codebases that grew too big and too
difficult to reason about by a single developer or even a team of
developers, their complexity has reached a point where changing even
just a couple of lines of code can have unintended and unknown
consequences in other parts.
The first thing we need to lay down here as a foundation is that
monoliths are not inherently bad. There are multiple companies that
have built successful IT businesses on monolithic applications.
As a matter of fact, monoliths are actually great for growing your
business. With small administrative overhead, you can add more
features to your product. The ease of importing modules with just a
couple of key combinations in your IDE makes development a breeze
and gives you rushing confidence about delivering a lot of code (be it
high quality or low quality) to your employer. Just like most growth
processes in life, companies, and with that, software, needs to start fast
and go through rapid iterations. Software needs quick growth so the
business can get more money, so the software can grow more, so the
business can get more money. You get where this is growing. So the next
time you attend a conference and hear a speaker say that monoliths are
systems of old design, make sure to take it with a pinch of salt. As a side
note, I would like to mention, that if your startup is struggling with the
maintenance of your legacy monolithic application, it is usually a sign of
a healthy business.
However, tendency shows that this rapid growth tends to slow
down as often over time reliability and scalability of software gets more
and more important. Having a single application might earn your team
fast deployment and easy-to-maintain infrastructure, but it also means
that the mistake of a single engineer can bring down a whole
application. The more people start working on a single application, the
more they start disturbing each others work, the more they need to
have unnecessary communication and the more they need to wait for
their builds and deployments.
Imagine the following situation: you’re an infrastructure engineer
working for a company that streams videos as a service over the
internet. The company is struggling, but somehow the CMO manages to
get the government of your country to stream the presidential election
speech. This is an amazing opportunity for your company to grow, so
there’s a lot of investment going into making sure that the system takes
the load well. The weeks before the event, you’ve done plenty of load
tests and instructed the backend engineers to fix certain parts of the
code that is not performing as it is supposed to. You’ve convinced the
COO to pour some money into heavier infrastructure, so the load will
ease over the system. Everything looks perfect for the speech and
you’re anxiously waiting for it with your colleagues at the time of the
event to experience the marvel of what you’ve been working on with
such dedication in the past couple of weeks. Then it happens. Right
before the speech, the stream stops. You have absolutely no idea what is
happening and start furiously looking for answers. You try to SSH into
the machines to no avail, getting rejected without remorse and the
minutes are passing. It’s been 13 minutes for the outage and the speech
is nearly over. Twitter is on fire tagging your company on where they
can watch the presidential speech and blaming the incompetence of the
CEO. In a furious rage, decide to hard reset the machines on the cloud
provider website that you’re using, but it’s too little too late. The event
is over. Millions are disappointed and the company is not in a very good
shape to get the next round of investment. 2 days later you get back to
work and start doing some investigation on what had happened. Turns
out, the ads team has rolled out some changes 2 days earlier that
caused a memory leak in the backend application. The memory on the
servers got full and blocked all processes. This was when you started
dreaming of a better and more reliable future for your company’s
infrastructure.
Figure 1-2 is a simple illustration of what had happened at this
video streaming company in the application.
Figure 1-2 A full outage caused by a tightly coupled broken component
The story above, albeit completely made up, happens in the life
cycle of every successful software system and every successful software
company. If you think Facebook or Google have never had hour long
outages at important moments in their lifetime, you’re very much
wrong. You can find documentation about various Google1 outages
online, with (sometimes) detailed descriptions on what parts of the
system caused this and that parts to be down for this and that amount
of time. After these outages they learn, adapt and make their systems
more resilient so the same problem doesn’t occur again.
There is an aspect of monolithic applications that many people don’t
think about that I like to call the “monolithic waterfall” or “cascading
monolith” architectures. This basically means that when you’re working
on a monolithic application you’re almost encouraged to design the
architecture of your code and your data in a monolithic way. Designing
interfaces around your modules becomes a chore and just overhead, so
you just import the line that you need. Adding a new database for
subscription information takes way too much time and would just
introduce more complexity, so you create the models in the same
database as your user and product information resides. If you’re
working on a monolith, all layers of your code and architecture will be
monolithic. Naturally, strict coding guidelines, architecture principles
and a challenging engineering culture can build and maintain a
monolith with clear internal interface boundaries that can later be
broken down into microservices with more ease.
Now, it would not be fair to not mention the benefits of monoliths
again here at the end of this part. All horror stories above and
negativities aside, the recommendation is to grow your business and
your engineering by utilizing the monolithic model. Just make sure to
keep a tight grip on the steering wheel and everyone is on the same
page about technical debt.
Now that we have an understanding of how a monolith looks and
acts like, we will take a look at it’s counterpart for the book, the
microservice.

Understanding the Microservice


Just to recap: a microservice is a single purpose software application
that resides somewhere on the web, is a small-ish codebase and can be
reasoned about easily even by a single engineer.
Just like we learned about monoliths that they are not the spawn of
Satan, we are going to learn about microservices that they are not a
silver bullet either.
Let’s go back to our infrastructure engineer in the previous story.
After the incident he ran a post mortem (if you don’t exactly know what
that is, don’t worry, we will explore it later in the book) with the rest of
the company and came to the conclusion that one of the best solutions
that the company could take to avoid such catastrophes as they had a
couple of weeks ago during the New Year’s Speech, is to adapt and
implement a microservice based architecture and leave the monolith
behind. He outlined the costs that it would take from the engineers and
the investors and made sure that everyone understands the benefits
and drawbacks of a migration. Soon later, the board gave a go to the
project. Some time later the company already had a dozen of services
running in the cloud (still including the remainders of the monolith),
and another campaign kicked in. This time the load was high, but the
system kept resilient. Despite the chat services going down, the video
playback still worked, making sure that the company reputation is
intact and the investors have put their money in a good place. Our
engineer went back to bed knowing that there will be no issues ever
again around the core business and lived happily ever after. In the
following figure 1-3, we can see how we lost our coupled architecture
from our previous figure and only have a partial outage now.

Figure 1-3 Components that are loosely coupled might only cause partial outages
Is that it? Well, no. In the above story our company had a service
that ran the chat systems, but the core business was still most likely
residing in the monolith. If the chat system were there, it is completely
possible that this marketing campaign would have been a disaster as
well, causing the end of the company for real. In conclusion, building or
extracting even small modules in your system can cause big wins in
critical situations.
You can hear dozens of these amazing stories when you go to
conferences, I myself gave a couple of them. In most of these success
stories there is a small but significant thing that the presenters
(including myself) don’t really like to talk about. This is the amount of
time that was invested into making sure that a systems that is
described above works on a software level and works on an
organizational level as well. In most cases implementing a working
microservice architecture takes years of engineering work which
involves not just coding, but architectural plans, vast amounts of
tooling, research of current systems, release plans, meetings, meetings
and meetings, and last but not least, patience.
Keep in mind that a switch like this can be an excellent way to
enable engineers in your organization to grow and to test their
knowledge not just in technical but organizational matters as well. It’s a
great opportunity to retain senior engineers at your company and to
enable regulars and juniors to explore new frontiers of the full stack
that they didn’t need to touch yet.
At this point, it might seem like a great idea to start your entre
architecture with microservices. Let’s explore this option in the next
section.

Early Design Choices


Speaking from experience, one of the biggest mistakes a company can
make nowadays is starting building their architecture using
microservices. Albeit the tooling of today is vastly superior to the
tooling of let’s say 5 years ago. We have amazing orchestrators, like
Kubernetes, containerization tools, like Docker, various services on
AWS, like EBS that help us build and deploy services. However, despite
the amazing tooling, development could go to hell very quickly.
The thing that a business needs in the beginning (as we already
talked about this briefly) is agility. Rapid changes on the data, logic and
presentation level to ship as many user features as possible. Designing
and building services, on the other hand, take time, dedication and
hardcore processes. Subsequently, starting your engineering culture
and development processes with a microservice architecture might
lead to a disaster.
I myself worked in a system that was designed from the get go to be
“microservice” oriented. On paper, everything looked fantastic. The
services had clear interface definitions and all of them had owners.
These services got compiled together and communicated with each
other through an asynchronous, event based system. The build process
used a very established build orchestrator as the base system and was
optimized to help all the engineers succeed. After so much praise you
can expect that the result was negative. Yes, it was. Everything looked
perfect in theory, but most of the things failed in practice. The systems
were too distributed and dependencies became a burden instead of
enablers. Engineers needed speed and not a system where they needed
to bump versions every single component when they updated another
one. Maintaining the interface definitions became a nightmare after a
while as it was difficult to understand cross-dependencies and
versioning among the components. Engineers were looking for
customized and unregulated shortcuts more than they were engaged in
the current working methods. The build system, albeit very
professional, was deemed to be too early for it’s time, slowing down
developers more than enabling them to speed up development.
Later on the company decided to merge together the microservice
architecture into a monolithic application and things started to speed
up afterwards. Ultimately proving the system to be successful.
Eventually the codebase grew too big and teams started to think about
ways of splitting it again.
Was it a bad idea to start with microservices? Was it a good idea to
move to a monolith, whereas the engineering norms dictate that you
should be moving into another direction?
The answer to the first question is not so obvious. If the company
was bigger, the engineering culture was designed around this type of
architecture, and there would’ve been more time invested into tooling,
then probably it would’ve worked out. However, mid to small size
companies often cannot afford the dedicated engineers for tooling.
Large companies, with spare capacity on their hand, on the other hand
can design their systems using these philosophies from the get-go.
As for the second question, no matter who you ask, the answer will
be a resounding yes. In this story, one of the great exemplars is the
ability to be able to look back and take two steps backwards to make a
gigantic leap forwards on the long run.
One of the morals of the story is that in order to make this leap, you
need to understand not only the technologies and the best practices in
the industry, but you also need to understand your business,
organization and the people who work at your company as well. What
might work for other companies (and in some cases even just other
teams in your engineering organization) might be a huge misstep for
you.

Summary
In this chapter, we have learned the basic linguistics that you can use
when talking to your colleagues about microservices over office coffee.
We’ve also learned that monoliths are not inherently bad, they can even
help grow your business just as rapidly as microservices can slow you
down if you use them at the wrong time, but in the long run, can change
the way how your users interact with your systems for the better. In the
rest of the book, we are going to explore exactly what is required of you,
the engineer, product owner, architect, to make sure that adapting to
this mindset of development will be a good addition to your company
and not an agile disaster.

Footnotes
1 https://googleblog.blogspot.com/2014/01/todays-outage-for-
several-google.html
© Akos Hochrein 2019
A. Hochrein, Designing Microservices with Django
https://doi.org/10.1007/978-1-4842-5358-8_2

2. A Pinch of Django
Akos Hochrein1

(1) Berlin, Germany

One of the most important considerations that one needs to make when
designing software services is the programming language and the
frameworks associated with it to use during the project.
For educational purposes in this book we are going to use the
Python programming language with the Django Web Framework and
associated toolchains to achieve our goals. To catch up out knowledge a
little bit, we are going to go through the core concepts of Django and
build a service ourselves.

Introducing the Problem


In this book, we will aim to stay to problems that are as close to real life
as possible. So we are going to work with business requirements and
try to follow the service design progression of an entire product, not
just tiny parts of it. Here is our problem space for the following pages:
Tizza. Tizza is a mobile first application in which users can decide
by photographs and descriptions of pizzas if they like them or not.
Upon liking a place, the user will receive notifications of group visits
organized to the given pizza place using the application. The end user
has a friends list, which they should be able to manage. There can be
settings for private (friends only) and public (not just friends) events by
the user.
Naturally, our company needs to make money somehow. For this,
we collect advertisement/ranking money from pizza places to be on our
platform. Depending on a sales system, we need to determine where a
company stands in our rankings and what order the end users should
see the restaurants.

Getting Started
Right before we get heavily into service design, we are going to run a
couple of commands in our terminal to get started with our Django
project.

Note it is highly recommended to structure your code and


dependencies into virtual environments or containers. If you are not
entirely familiar with these concepts, I highly recommend checking
out Python development with virtualenv or Docker.

To install Django, all you need to do is run the following code in your
terminal:

pip install django

When we see a Django application running as a whole, we call that a


project. To create a Django project, you simply need to execute the
following command in your terminal:

django-admin startproject tizza

With this, a simple Django application will be created in a folder


called tizza, as shown in Figure 2-1.
Figure 2-1 Bare django folder structure
What if I told you that at this point you already have a functioning
website? Type the following in your terminal:

python manage.py runserver

And in your browser access http://localhost:8000


You should see the screen in Figure 2-2.
Figure 2-2 Django has successfully been installed
Congratulations! Now the real work starts.

Django Apps
Django has a second layer of logic in its general folder structure. These
are called apps. The naming might be a bit confusing, since they have
nothing to do with software running on your smartphones. Apps are
usually used as logical separators between business cases and/or
features in your application. You can think of projects as being able to
orchestrate between different apps, whereas one app can only belong
to one project. To create a new app, we simply need to run the following
command:
python manage.py startapp pizza
Now our directory structure has been updated as shown in Figure
2-3.

Figure 2-3 Bare django folder structure with app

Some applications are by default in Django projects, so we don’t


need to deal with them every single time we create a new project. They
are installed with Django itself, that’s why you don’t see them in the
folder structure. One of these is the auth application that contains tools
for user creation and authorization. Another one that we are going to
utilize heavily is the admin package, which gives us a great deal of
control over the data of our application.

Models and the Power of ORMs


Whenever you receive a new feature or start working on an entirely
new product or application, the first thing you usually need to think
about is the data that is going to drive it. Once the data is figured out,
with the power of Django and ORMs, we can get started immediately.

What are ORMs?


ORMs (or Object Relational Mappings) serve as an abstraction layer
between the database and your application. You don’t want to create
marshaling and unmarshaling code every time you run a raw query on
a database. We are not only talking about issues of bugs, but also huge
security problems that these unprotected systems can have.
Instead, we are going to use ORMs, most languages and web
frameworks have something similar in place. For Python developers
that don't use Django (or don’t need an entire web framework), there’s
SQLAlchemy. For PHP developers there’s Doctrine, for Ruby enthusiasts
ActiveRecord. In short, I strongly recommend to start using and get
used to ORMs, if you haven’t already, as they will make your and other
developers life in your company much simpler.
To give you a bit more on ORMs, imagine the following situation:
you’re an engineer fresh out of school, eager to work the living hell out
of your first job, which is the maintenance and extension of a web
application. The first task that you get is to fetch and display some data
from the database. Luckily you took database and networking classes,
so you have a vague idea on how the data should be flowing. The first
piece of code you write is shown in Listing 2-1.

import database

def get_pizzas(pid):
cursor = database.cursor()
return cursor.execute(f"""
SELECT * FROM pizzas WHERE id = {pid};
""")
Listing 2-1 Simple query to get a pizza

The code is not awful, per se, however, there are a couple of pretty
serious issues with it that experienced engineers might have noticed
already:
Another random document with
no related content on Scribd:
sossegar à vontade. Ainda agora chegou. Se dá mostras de
impaciência, o que está à frente abespinha-se e redargúi: «¿Que
está o cavalheiro a fungar? Há uma hora estou cá eu». E a gente
curva-se. Passa a olhar o sujeito respeitosamente. Caramba! «uma
hora!» E tudo são cogitações. ¿Mas não há quem nos atenda?
¿Não há quem nos despache? Há sim, senhores. Há um tipo que
está lá ao fundo chupando uma beatazinha, mãos nas algibeiras e
dizendo, para outro matuto sorna como êle: «O cházinho era
delicioso! E então os bolos. Os bolos, menino!...»
«Eu estou aqui há duas horas!» diz um escanifrado que agita uma
carta. «Espere se quiser, diz o dos bolos. Há muito mais tempo
estou eu cá e não faço tanta chiada!»
¿Os senhores nunca foram pagar a décima? Não foram? Felicito-
os.
Pagar a décima é tambêm uma cousa divertida, para quem não é
cardíaco, nem tem aneurisma nenhum. Eu fui uma ocasião, mas à
cautela levei lunch, um couvre-pieds e um romance para ler. Não
foram prevenções inúteis. Fui para lá ao amanhecer e havia
candieiros acesos. Li o romance todo e comi até as migalhas do
lunch. Comeria outro, se o levasse ou não receiasse perder o logar.
Porque aquilo é à vez. Uma pessoa, munida do competente papel
intimativo e do dinheiro para a ressalva, apresenta-se. Quando
chega, há já uma linha de pessoas que vem até à rua. Umas ficaram
de véspera, outras foram ainda de noite e as que foram assim
quando os galos cantam e a aurora rompe, já encontraram três
dúzias delas à espera. Outras vão chegando,—já se sabe, o
competente farnel, o cobertor e o livreco—e tomam logar. Ás onze e
meia—a repartição abre às 10—chega o garimpo que varre a casa.
E é um tropel de gente que se empurra, que toma logar, que se
instala. Neste apertão é vulgar perder a carteira ou ficar com um
calo esborrachado. Mas tudo vai bem. A gente sentou-se, apara a
paciência, abre o livro. Meio dia. Entra o pastinha. Depois entra o
outro, depois o recebedor. São as feras. Há uma grade entre elas e
o público, e um postiguinho, por onde a gente lhe mete a massa,
que é como quem diz o sustento.
Começa a chamada. O patife parece que está a entoar
cantochão. Vem ainda estremunhado. Entretanto os que não
levaram livro vão contando a vida aos vizinhos. «Eu moro na rua da
Ametade. O meu nome é Simão. O meu pai é timbaleiro. Minha mãe
era parteira...» Ah!... O meu vizinho ressona de assobio. Um velhote
quere dormir mas a conversa dos dois grulhas não o deixa pegar no
sono. Bem: ainda há 44 adiante de mim. Eu volto à leitura. «José
Ferreira Casmurro!» Pronto, diz o outro. É a chamada que continua.
E os outros pensam: «Aquilo é que é um Casmurro com sorte». Ah!
quanto falta para lá chegar?!
Aqueles bandidos não teem nenhuma pressa. Vão tranqùilamente
zombando do tempo e da paciência dos outros. Passa uma hora,
passam duas, passam três. Ao meu lado havia um petiz de ano e
meio que mamava como um danado na têta da mãe, quando eu
entrei. Quando se chega quási à minha altura alguêm do lado toca-
me no ombro. Volto-me. É o petiz que interroga e pede: «¿O
cavalheiro não tem por aí um cigarrinho que me dê?» Como êle
cresceu, o brejeiro!
Emfim, na rua! Caramba, mas é de noite! Como o tempo passa! E
aquilo lá dentro continua. Uff!
Quem diz registos e décimas diz tudo. «Olhe, venha amanhã!
Olhe, espere! Se tem pressa, vá andando». Emfim é um nunca
acabar. O que se resolveria em qualquer parte num quarto de hora,
em Portugal leva um dia, uma semana, um mês, um ano, uma
eternidade. Isto é o país das eternidades. Primeiro que as cousas
cheguem...
Eu jogo não sei há quanto tempo com uma cautela de três na
lotaria. Sempre o mesmo número. Pois para verem como Portugal é
o país do amanhã, só lhes direi que é rara a lotaria em que a cautela
me não sai branca. Ora não sei se os senhores estão a ver que se
fôsse em qualquer outra parte já me teria saído a sorte grande...
Mas o que me consola é que o tempo virá e acabará com o meu
dinheiro, com a minha vida, com o número em que jogo, com a
grande, com a lotaria, com a Santa Casa e até com a lembrança de
tudo isto.
E não sei se os senhores estão a ver que isso será uma
felicidade...
A decadência do jornalismo em
França
UM articulista parisiense, parisiense pela finura da sua expressão,
pelo subtil da sua análise e sobretudo pela leveza scintilante da sua
prosa, Ibels, acaba de declarar decadente o jornalismo francês. E
vem, com uma santa ingenuidade, uma destas ingenuidades para
medalha de ouro, e um espanto nada correcto, nem do mundo, dizer
que o jornalismo francês decai porque o que lhe falta são jornalistas;
porque os artigoleiros são muitos e os articulistas são poucos e
porque finalmente êle é o eco de tôdas as chantages, o eco de
tôdas as calúnias, o gramofone de tôdas as mentiras e o acusador
de tôdas as reputações. E, indignado, prossegue: «O periódico
moderno pratica a medicina ilegal, recomenda venenos, serve de
intermediário entre donas de casas suspeitas e jovens de menor
idade. Insere e entretêm a correspondência amorosa e adúltera e
vai mais longe, publicando um boletim financeiro em que milhares
de môscas caem prisioneiras vendendo os seus títulos porque
acreditam na sinceridade do periódico que lêem». E diz mais, que
isto, que aquilo, resumindo que é tudo uma pouca vergonha
desaforada. A propósito, para não perder pitada, ferra uma tunda no
Le Matin, que na sua opinião é um intrujão que já de há muito
deveria ter a redacção instalada numa das celas da Penitenciária de
lá.
Eu não conheço Ibels. As suas conclusões parecem-me
acertadas. Mas o que acho interessante são os seus espantos.
Admira-se. Admirar-se a gente é mau sinal. O Eclesiastes tinha dito
que nada de novo há debaixo do sol. Ora a pouca vergonha é mais
velha do que o Eclesiastes. É talvez mais vélha do que o sol. Mais
vélha do que o sol, do que os deuses, do que a terra e do que tudo
quanto existe. A pouca vergonha é eterna. Não tinha pois de que se
admirar. Eu é que me admiro (oh, santa incoerência!) do seu
espanto.
A decadência do jornalismo em França vem de longe. Balzac já
lhe estudou as causas nas Ilusões Perdidas. E caso curioso, nas
Ilusões havia tambêm um Luciano que se admirava. O articulista de
agora é o Luciano de ontem. Está escrito: «Hão de existir Lucianos
em todos os tempos!»...
Quem quiser saber destas cousas sem o tom acre de censura e
lamento que perfuma o artigo de Ibels, antes com o tom risonho de
quem está muito à sua vontade—como quem está em sua casa, por
exemplo—deve ler um curioso artigo em tempos publicado na
imprensa espanhola. Chama-se Esplendores y miserias del
periodismo. Assina-o Gomez Carrillo, cronista do Liberal, creio eu,
literato de Espanha vivendo em Paris e artista urbi et orbi onde vá a
língua de Quichote ou a respectiva tradução. Aí é que se diz tudo!
Tudo e ainda mais o que disse Paul Pottier, homem lido e sabedor.
—Ora diz Carrillo, e escreveu Paul Pottier, que «para 600 empregos
no jornalismo há 3.000 jornalistas». ¡E se êles, todos êsses pobres
concorrentes, soubessem o que os espera! Uma vida sugante e
angustiosa. Nem horas de comer. Dormir incerto. São os cavalos de
posta da notícia. É preciso lutar, lutar sempre. O que chega a Paris
cheio de vontade leva um dêstes abanões que quási o deitam a
terra. O jornalismo é uma luta. Não há jornalistas, há cavalos de
corrida. ¿Qual dará o artigo, a notícia, o comentário mais
desenvolvido, mais agaçante de pormenores, mais chorudo de
minudências, mais dramatizado de bagatelas? O público quere. O
público aguarda. Quere cousas novas, cousas inéditas, cousas
imprevistas. Um assassínio? Isso é vélho. É preciso achar novo.
Não há? inventa-se. Saber inventar, eis a questão em ocasiões
difíceis.
Ao cabo de três anos num logar subalterno, tendo dado tudo o
que trazia na cabeça, tendo gasto todos os seus nervos, puido tôda
a sua vontade, sem nada no estômago porque se alimentou mal e
irregularmente, com uma neurastenia aos ombros e o vácuo no
cérebro, a criatura é corrida a pontapé do jornal e vai direitinha a um
manicómio onde nunca mais a endireitam.
Os grandes jornais baixam as suas tarifas de pagamento. Quási
todos desceram a linha a 15 cêntimos, com excepção de Le Temps
que paga 30, Le Figaro que dá 25 e Le Gaulois e Gil Blas que não
dão mais do que 20. É certo que Catulle Mendés cobrava de Le
Journal quarenta mil francos anuais, sejam sete contos e tal. Mas Le
Figaro, que ontem dava a Huret 2:000 francos, não dá hoje a Serge
Basset pelos teatros senão 1:000.
Harduin no Le Matin recebe 1:500 francos, com obrigação de
escrever todos os dias um minúsculo artigo. Sarcey recebia de Le
Temps 1:000 francos mensais pelos seus artigos. Octave Mirbeau e
Severine, que no Le Petit Parisien recebiam importantes honorários,
foram dispensados da sua colaboração. E os contos que Fernand
Xau pagava a 300, 250 e 150 francos baixaram a 25, e últimamente
a 15 francos. E isto em jornais que tiram milhões de exemplares.
Os nomes cotados fazem-se pagar bem. Porêm para os que
veem sem nome, para êsses, o caminho da imprensa é um calvário.
São recebidos com duas pedras na mão; exactamente como no
tempo em que Luciano queria o logar de redactor no periódico que
tinha por Cerbero o vélho militar. E devemo-nos lembrar de que
todos os citados são os bem pagos: os da fôrça de Mirbeau, por
exemplo, que só com um artigo fêz o nome a Maeterlinck...
Considerai o que não será agora nos subalternos?!...
Um escritor que viva de escrever e que tenha já uma pequena
voga vê-se obrigado a rebentar com trabalho para cobrar um
estipêndio rasoável. As revistas não lhe publicam um artigo senão
de três em três meses pelo menos, para não repetirem o nome do
colaborador; os grandes jornais, de que êle vive, baixam-lhe dia a
dia a tarifa. Os artigos reunidos em livro dão uma bagatela. Os livros
que são enviados ao periódico, para criticar, vendidos e regateados
não dão para o alfaiate. De maneira que a criatura vê-se e deseja-
se.
Isto é tendo certo nome, porque de contrário nem as revistas lhe
aceitam artigos, nem os grandes jornais lhe abrem a porta, nem os
livros lhe chegam à mão.
E a tanto chega o descaramento que Magnier, senador, que
largos anos possuiu L’Evenement, dizia aos seus redactores: «O
que preferem os senhores? ¿Que lhes marque um ordenado de 500
francos por mês e não o pague ou que lhes dê 250 para os pagar?»
Quer o redactor aceitasse uma ou outra proposta, sabido era que
não via cinco réis. E a maneira de alguma cousa receber era
negociar com êle uma parte da página dos anúncios. Se não andava
depressa na cobrança ficava sem real, porque o director mandava
tambêm cobrar. E quantas vezes o redactor ao chegar não soube
que os anúncios já estavam pagos...
Êste Magnier era caloteiro contumaz. Conta-se que Aurelien
Scholl, a quem êle devia certa soma e não tinha maneira de a
receber, uma ocasião ao ver passar o seu trem correu para êle,
desprendeu os cavalos e foi vendê-los ao Tattersall. Foi uma
inspiração divina. Senão podia dizer adeus ao débito.
A imprensa francesa explora o escândalo, explora o público,
explora todo o explorável. Até aqui muito bem! Que há nisto de
estranho? ¿Pois não é natural que meio mundo explore a outra
metade? E Ibels, indignado, cita o Panamá, cita mil casos em que o
«periodismo» tem sido nefasto. E deixa, o maroto, ficar no tinteiro a
questão Dreyfus.
O jornalismo tem bons e maus. Que êle esteja decadente, não
acredito. Êle é o reflexo do seu tempo. Exigir jornais sãos numa
sociedade podre parece-me exigir de mais. De acôrdo que os maus
sejam mais do que os bons! Mas isso que importa? Se às vezes um
jornal só, um homem com uma pena na mão, fica nos séculos,
sobreleva acima de tôda essa podridão, de todo êsse enxurro, de
tôda essa vaza, cujo mau cheiro só o tempo purificará?!
Que importa, se um brado de Justiça vale mais do que uma
multidão berrando, e se um jornalista de consciência vale mais, tem
por si só mais fôrça do que um grande exército?!...
Que o jornalismo está decadente? Embora. Êle é ainda a árvore
onde de tempos a tempos se empoleira uma criatura para dizer que
o manto, o celebrado manto de el-rei da fábula não passa duma
hipocrisia ou duma cegueira.
O Carnaval
EU não posso folhear atentamente a obra de Rafael Bordalo sem
me demorar nessa página suprema, traçada num minuto de tédio e
feita num instante de aborrecimento: A última máscara. A última
máscara é, escusado dizê-lo, a máscara da Morte. Se a do feto é a
primeira máscara, a da caveira é a última. A última máscara, de
Rafael Bordalo, representa pois a caveira.
Esta vida são três dias, diz-se. Êsses três dias simbolizam as três
idades. O Carnaval são três dias, que tantos são os da vida. Esta
vida é pois um carnaval. Murger chamou-lhe uma «máscara de
forçados» outros lhe teem chamado o que melhor lhes tem parecido.
Não inquiramos. Assunto complexo, se se quiser explicar, traz
consigo complexas deduções. E não há assunto mais complexo do
que a Vida.
O carnaval que a gente vê, ou por outra que a gente viu, é bem
pior do que aquele de que a gente se lembra e bem melhor do que
aquele que se verá. O carnaval tende a desaparecer. A graça
foliona, travêssa, doudejante, morreu. O que por aí anda é outra
graça, uma graça que sorri nos intervalos de tosse e nos intervalos
do riso mendiga dez-reisinhos.
Se não, é ver-se como a fôlha mais bem escrita do Carnaval é a
de quarta-feira de cinzas, esta quarta-feira em que vos escrevo,
satisfeitíssimo por ter visto as ruas despejadas de mendigos
enfarinhados, mendigos pierrots, mendigos chechés, e
mendicidades ambulantes, danças, paródias, filarmónicas e tutti
quanti. Passou a época das tremoçadas. Chapéu alto que passava
era penante dado ao criador. Ninguêm se aventurava a sair.
Despejavam-se barricas de tremoço sôbre o desventurado que ia
assim mais asseadinho.
Uma criatura saía. Á saída da porta levava logo com uma luva
cheia de areia pela cara que ficava azul. Andava mais um minuto e
era uma assuada. Cada minuto cada nova aventura. Algumas de
que saía mal-ferido. Á hora de jantar, quando a criatura recolhia e se
inventariava, via com desgôsto que o chapéu estava inconcertável.
A farpela cheia de farinha, com um ovo feito em estrêla nas costas,
seis farpões de rabos postos e arrancados. Um ôlho a menos. O
colarinho zebrado com uma longa lista de pós de sapatos. A
camisola cheia de areia, a guedelha cheia de farinha e as botas—
ah! as botas!—cheias de lama—porque soe chover quási sempre
pelas entrudadas,—e a chuva é o protesto do infinito.
Vejam lá hoje. Tantas são as leis publicadas sôbre o Carnaval que
a gente se vê na absoluta necessidade de consultar um advogado
sôbre se será prejudicial atirar uma serpentina.
O advogado consultado promete estudar. Estuda e apresenta a
sua resposta quarta-feira de trevas, ao mesmo tempo que apresenta
a conta da consulta. São pelo menos 2$500. Vejam lá se há cousa
mais interessante.
Antigamente a criatura, depois de borrifada com urina, zurzida de
tremoços, mascarrada de pós de sapatos, enfarinhada, maçada e
enlameada, recolhia num bolo, mas alegre. E resumia para a
família:—Aquilo é que foi divertir! Agora não. Sai de chapéu alto,
escovada, correcta, exactamente como se fôsse para aquelas
recepções da embaixada
em que há uma duqueza que sorri, «tão branca, tão decotada» que
até dá vontade de a gente resumir, ao recolher a casa:—Ai, filha,
que papança, o que traduzido em vulgar quere dizer:—Ai, filha, que
maçada!
Ah! o Carnaval civilizado! ¿Já viram maior pouca vergonha?
Antigamente a gente não saía. Agora, sabendo que volta com o
arranjinho como foi, sai. Sai, e volta abrindo a bôca, espreguiçando-
se, moída, sem ânimo, farta de ouvir baboseiras e de ver misérias
ambulantes. As ruas são tristes. Os bailes são quási macabros. As
mascaradas são lúgubres:—¿O cavalheiro dá licença que eu lhe
atire êste saquinho de bombons?—Pois não! ora essa! O cavalheiro
atira. A gente guarda. Chegando a casa abre o saquinho. Não são
tal bombons. São feijões, são tremoços, é grão de bico. Comentário
—Que intrujice!
Se abstrairmos do Carnaval e volvermos os olhos misericordiosos
sôbre esta mascarada em que todos entramos, uns mascarados de
sinceros, outros de cínicos, uns vestidos de moços fidalgos, outros
de moços de fretes, uns vestidos de archeiros, outros de par do
reino, a desilusão resulta pior. Porque, bem considerando, tudo na
vida é mascarada e tudo são máscaras. ¿Por que razão é que,
tendo um homem nascido nu e entrado na morte como a mãe o
depôz cá neste mundo, essa súcia inventou que um bocado de
galão dourado pôsto num braço provoca um gesto de submissão, e
pôsto num caixão nos faz pensar nas vaidades de todos os galões e
de todos os gestos? ¿Por que razão é que quem «rouba um milhão
é barão e quem rouba um pão é ladrão», como diz o poeta? Tudo se
mudou. «¿Antigamente não eram os ladrões pregados nas cruzes e
não se pregam agora as cruzes nos ladrões?» Fala certo Junqueiro:

E não estala um ai de dôr em cada peito.


E não submerge o monstro a cólera do mar,
E a terra continua em seu girar perfeito;
Ó Chimera, ó Tristeza, ó Justiça, ó Direito,
Providencia onde estás, que te quero insultar!

A indignação passa, a miséria fica. E para que há-de a gente


considerar em tanta miséria?!
É fatal. Se a gente scisma e se ensimesma, pobre dominó
sentimental! Dominó lunático, sonhador escarnecido! Se a gente
ama, pobre tolo, que anda na lua. Se acredita, que assuada! se
considera, que filósofo! E não há que scismar, que sonhar, que
amar, que acreditar e que considerar. É deixar-se ir no vortilhão,
como quem aborrecido vai na onda, empurrado, sem sentir os
empurrões, escarnecido sem ouvir os escárneos, apupado sem ter
ouvidos para os assobios. Em resumo: É a vida um baile de
máscaras muito aborrecido. Entra-se julgando a gente divertir-se
imenso, e, quando se chega a quarta-feira de cinza, encontra-se,
depois de muita maçada, morta de aborrecimento e de tristeza com
êsse dominó embuçado, misterioso, que tem um riso eterno e que é
o porteiro da saída. Êsse dominó é a última máscara. É a ultima
máscara que mudamos e é o último mascarado que encontramos.
Como Rafael Bordalo deveria estar morto de tédio para fazer a
síntese duma filosofia num quarto de papel—a síntese da filosofia
do riso, porque o riso é uma filosofia em que sempre se acaba a
chorar.
Mascarada! Mascarada eterna! Mascarada que veio através dos
séculos até nós e de nós irá por êsses séculos sem fim. Mascarados
que todos nós somos. Quando falamos mentimos, quando juramos
mentimos. Quando tentamos falar verdade ainda mentimos, porque
a verdade não é mais do que uma mentira menos mentirosa. E,
senão, que nos mostrem algum amor que o seja, algum amigo que
não falseie. O amor—uma Colombina e um pierrot—Mas livra-te de
amar, porque serás o pierrot traído. A amizade—uma espada que se
quebra ao sair da baínha para nos defender. E entre outras
desilusões, de vez em quando passa por nós sorrindo a última
máscara, de Rafael Bordalo.
Eu invejo os que se divertem. ¿Como serão feitas lá por dentro as
criaturas que se divertem? Não sei, e creio que nunca ninguêm o
saberá. Invejo-as, porque não sei se elas existem. Acho mesmo que
as criaturas nessas condições estão em igualdade com a do feliz,
que Manuel Bento de Sousa pôz em quadras. O sultão, para se
restabelecer da sua grave enfermidade, precisava nem mais do que
da camisa dum homem feliz. Embaixadas, expedições, o demónio e
nada. O homem feliz não aparecia. Interrogados os súbditos dos
seus estados, à uma todos responderam que não, que não eram
felizes. Só um pobre, que puxava a uma nora e cantava, respondeu
que sim. Êle possuia essa cousa tão rara como o amor e como a
amizade. Êsse era feliz. Foi o pobre diabo amordaçado e conduzido
sôbre um camelo à presença do régio doente. Era a cura. Mas logo
que o despiram se verificou com espanto que êle,—o homem feliz,
—nunca tivera camisa.
É bonita a história, ¿mas quem nos diz se não será mentira?
¡Sucedeu há tanto tempo e num país distante!
E com estas e outras histórias, umas cómicas, outras trágicas, se
passa a crónica e a vida. E depois à saída do baile, lá espera o
dominó fatal.
É por isso que eu me demoro, sempre que folheio a obra de
Rafael Bordalo, nessa página que representa a última máscara.
Academias
NÃO sei se os senhores teem reparado que muito ao contrário da
eterna verdade que Ibsen apresenta, no seu Inimigo do Povo,—«o
homem mais forte é o que está mais só», que tambêm pode ser
traduzida «vale mais só do que mal acompanhado»—o homem tem
uma extraordinária tendência para se reunir e dizer asneiras de
sociedade. E é fatal. O homem, alêm de tudo quanto é, ia eu
dizendo, Homo sapiens de Linneu, «o animal implume que ri» de
Platão, é tambêm palrador. Palrador, sim, meus senhores!
Prometam-lhe uma libra para estar calado uma hora. Ou diz ao fim
de meia, como o outro, que «meia hora já está passada», ou pedirá
ao fim de dez minutos de experiência, que guardem a libra porque
se não fala rebenta.
Tem uma certa razão, valha a verdade. «Para viver só, é preciso
ser bêsta ou Deus» disse Aristóteles. Nietzsche concluiu que há
tambêm um terceiro caso; ser as duas cousas: filósofo. Ora nem
todos são deuses, se bem que as bêstas abundem. Filósofos, não
vai o tempo para êles. E a um ou outro que vem, quási sempre por
engano, sucede-lhe a mesma cousa que ao Misantropo de Castilho,
aquele
«Severo Tristão de Matos»
que, depois de clamar, de se indignar e de ter estado não sei
quantas vezes em risco duma apoplexia ou duma congestão

«Saíu da vida presente


por farto de ver sómente
falsos, vis, ladrões e ingratos».

Provado, pois, que o homem tem necessidade de se assembléar,


para viver, logo foi inventar mil nomes para justificar a reunião. E
então chamou-se-lhe, de soirée—sociedade onde a gente se
aborrece, tendo ido para se divertir,—até Academia, sociedade onde
a gente se diverte, tendo ido para se aborrecer. Não é das
Academias recreativas familiares da rua onde a gente mora. É das
outras. Cousa séria, grave, ponderada, onde se discute ou se
dorme, mas quási sempre se dorme. Isto vem a propósito de termos
agora mais uma Academia.
Ora há muitos anos que a gente tem outra—ali para as bandas de
Jesus, que se chama, creio, Academia Real das Sciências. É uma
sociedade onde os sócios teem fardamento tal como a Incrível
Almadense ou a banda dos bombeiros de Chão de Maçãs.
Fardamento, chapéu armado e espadim. Para que serve, não sei.
Que tem feito? Quási nada. Um dicionário que ficou em azurrar. Ora
eu entendo que em vista de nunca ter passado do A, sendo já tão
crescidinha, se lhe dê outro ofício. Está provado que não nasceu
para aquilo. E o que é mais, não tem vergonha nenhuma. ¡Sempre é
uma tamanhona sem préstimo!
Bem visto, ela está no seu papel. As academias não se fizeram
para fazer cousa alguma. Academia é para a gente se reunir, fumar
a sua cigarrada, jogar a sua partidinha de dominó, com a municipal
à porta, mandar para a mesa duas cartas que o ilustre sócio
escreveu ali ou trouxe escritas de casa, dizendo—«Peço ao ilustre
presidente o obséquio de dar essas cartas ao contínuo para as
deitar no marco quando sair!» Ás tantas levantam todos a gola, dão
as boas noites e desandam para vale de lençóis.
Teófilo Braga disse uma ocasião em público: «Academia é uma
colecção de sábios, que caminha para o pedantismo». Foi muito
amável. Foi muito amável porque se alguêm quiser saber o que é a
nossa Academia Real, etc., consulte o Cancioneiro da Vaticana no
seu prefácio. Ali verá que nunca o Cancioneiro seria impresso se
não fôsse êsse benemérito sábio que foi em vida Ferraz de Macedo,
o antropologista. Porque para ser impresso pela Academia não
havia dotação e um dos membros da classe de literatura de quem
dependia a aprovação do Cancioneiro julgava que o texto era latim!
Mas há mais. Não havia dotação para o Cancioneiro, mas houve
perto de dois contos de réis para gastar com o embelezamento das
salas para a celebração duma sessão real, uma sessão solene.
Com o dicionário já se gastaram algumas dezenas de contos de réis
e não serve para nada, o estafermo. Não é caso para dizer «não
estala um ai de dôr em cada peito», mas «e não há um arrocho que
os desanque!»
Depois, ¿para que servem as academias? Que préstimo teem?
Eu não lhes conheço nenhum. Nunca de nenhuma Academia saíu
um homem de talento, e em compensão os que o teem e entram
para elas perdem-no logo. Senão digam-me a obra grande, de
utilidade ou de valor, que as academias tenham fomentado! Qual?
Nenhuma. Crer-se-ia na plausibilidade disso se Academia não fôsse
um vaso de víboras como o de Carlyle, víboras desdentadas,
invejosas e pequeninas, e que, para não deixar entrar nenhuma
ideia nova, nenhuma ideia grande, até pôs guarda à porta,
exactamente como à porta dos parlamentos se põe tambêm guarda,
que é para que a Justiça fique de fora.
Plauto, o cómico, não foi da Academia Real das Sciências.
Cervantes, tambêm não. Shakespeare tambêm não. Camões, idem.
Ora aqui estão uns mágicos que não precisaram, para entrar na
imortalidade, de apresentar o cartão de visita tendo por debaixo do
nome «da Academia Real das Sciências, da Sociedade Filarmónica
Capricho Recreativo, da Sociedade dos «tacões ao domingo, etc.».
E estou até desconfiado de que o porteiro, ao ver tal, e ter olhado
bem para a cara do sujeito, lhe diz com um risinho e uma
palmadinha no ombro: -«O amigo está enganado! Tem que descer.
Isso é na cave!»
Porque a imortalidade é o único logar para que a farda não serve
de passe de livre trânsito.
Malheiro Dias diz, nas suas Cartas de Lisboa, que «a mais alta
categoria social não vale uma farda de simples adido de embaixada,
com plumas de avestruz no bicórnio e folhagem de vinha e oliveira,
bordada a ouro, na gola»; pois com êste simples fardamento os
polícias fazem continências, os municipais abrem filas e a multidão
comprime-se para dar passagem. Isto ao subir a calçada da Ajuda.
Será verdade. Mas agora aqui me ponho eu a pensar que talvez a
farda não valha para a imortalidade, porque para ir para lá a Ajuda
não é o melhor caminho. Sim. Deve ser isso. Assim é que Plauto foi
moço de padeiro, Camões foi soldado e Cervantes soldado e
pobretão, e entraram. Camões tinha farda, mas quando morreu
estava no prego. Em compensação, dos ilustres fardados da
Academia, o porteiro não deixa lá entrar nem três. Vejam lá se vale
a pena gastar dinheiro no alfaiate quando o que é preciso é gastar
noites a fritar os miolos.
«Cá e lá más fadas há». Isto não é de nenhum dos escritores que
eu costumo citar. Isto é da sabedoria das nações. Os senhores já
sabiam?! Pois em França é tambêm assim, quando não pior. A
Academia dos Goncourts, fundada para dar um prémio ao melhor
romance, não tem estimulado nada o talento dos bichos que
concorrem. Tem-lhes estimulado mas é o apetite e a solércia. Não
os podendo fazer mestres em romance, fá-los mestres na
empenhoca. E por isso o premiado é sempre o que mais empenhos
tem. Pois então.
Não se desconsolem os que não são académicos. As academias
não são para todos. Isto é dúbio, bem sei, mas entenda-o cada qual
como quiser. E estou escrevendo e está-me lembrando a caricatura
de Zola feita por Gilbert Martin: Zola vestido de mineiro, cachimbo,
botas altas e lanterna, oferece o braço à Academia, uma vélha
esganiçada e tôla, ao mesmo tempo que lhe pisa a cauda. É claro
que a vélha escama-se e não dá o braço. E a propósito da
Academia e de Zola há outra publicada na Silhouette: Zola, com os
seus livros às costas, puxa o cordão da campainha da Academia.
Puxa, quebra o cordão e a porta não se abre. Zola não entrou.
Objectar-me-hão: mas queria entrar! Queria por estar a porta
fechada para êle. Por teimosia, por pirraça. Se lá entrasse o mais
certo era... vir embora.
Maupassant disse que três cousas desonravam um homem: a
Academia, as condecorações e a Révue des deux mondes. Depois,
passados muitos anos, prestes a morrer, escrevia na Révue, estava
para entrar na Academia e creio que era condecorado. Ironias do
Destino. ¿Quem sabe lá se eu um dia tambêm serei sócio da
Academia? Tudo é possível. Então serei um velhote grave,
ponderado, sério, terei óculos, um grande horror ao galicismo, um
poucochinho de pancada na mola, e uma coleira ao pescoço com a
chapa da casa. Todos êles teem. Pancada na mola e um bocadinho
de imbecilidade. Vai daí, a Academia forneceu-lhes a chapa para os
distinguir da outra gente, e para que as prendas se não percam.
Pois quando eu lá chegar, ia dizendo... Mas emquanto não chego,
¿os senhores dão-me licença que acenda um cigarrinho?...
O passado
DESEJAR a morte é ainda querer voltar ao passado. E assim como
há dias em que ser morto é a ânsia que me lança um baraço ao
pescoço e me afoga, outros há em que uma ânsia regressiva me faz
voltar atrás para tornar a viver sôfregamente os dias já vividos. Hoje
é um deles. Lá fora o céu pôs o seu «plúmbeo capacete». Por vezes
uma chuva miudinha e intérmina envisca tudo da sua frialdade. E as
almas, ressentidas de tanta fereza, voltam-se a viver o Ontem,
queimando o Hoje gélido na lareira das mornas recordações.
Recordar não é só privilégio dos vélhos. Lembrar, é ainda na vida
o único lenitivo.
Ai! o que seria a vida para aquele que não tivesse a memória e a
fantasia,—o Passado e a Ilusão.
Com a memória vive-se, com a fantasia sonha-se. Mas vive-se
deliciosamente e sonha-se um sonho ainda mais delicioso. Por isso
em dias assim,—um chuvisco frio minando as energias,—as almas
vivem e sonham. Lá fora há lama e frio. Cá dentro, acesa a fogueira,
principia o desfile.
Então não há recordação, carta de amor, beijo dado ou passado
dia, que não traga o seu quinhão. São pequenas cousas, cousas
mínimas que se transfiguram. A saudade vê sempre por vidros de
aumentar. Aí começa a gente a viver com fúria dias maus, que,
comparados com os de hoje, nos parecem bons, dôres sofridas que
cotejadas com estas, nos parecem verdadeiros prazeres. Ao fim,
quando aquela galopada furiosa desfilou, quedamo-nos encolhidos
scismando: como a gente envelheceu! E a saudade manda
recomeçar a sessão, como num animatógrafo em que a fita
recomeçasse a passar.
Como é verdadeiro o dito do poeta: «e saudades até doutras
saudades!» Sim! eu sinto isto. Não há dúvida. Uma grande ânsia de
ser pinheiro, de ser oliveira, árvore perdida, rocha bruta, me
atormenta. E a chuva cai.
O passado atrai-me. Os livros novos não me dão novidades, com
o seu papel de alvura fatigante e a sua sorna monotonia. Não, os
livros novos não são novos. Lembro-me de ter já lido isto! Aonde,
não sei. Mas de-certo tudo isto eu senti, tudo isto eu vi já.
Estes amores, assim rasos, assim secantes, já por mim
passaram. Estes versos já eu os ouvi. Tudo hoje à minha volta me
deixa frio. Hoje não há senão aridez e sequidão. É o simoun que
turbilhona, arrasta e sepulta.
Os vélhos livros, com suas páginas amarelentas e os seus
grossos caracteres, dizem-me não sei quantas vélhas saudades
inolvidadas. Assim compreendo a paixão dos bibliófilos avaros, dos
numismatas soberbos, de todos os coleccionadores e de todos que,
estranhos ao seu Hoje, ou chocados pela brutalidade dele, se
evadem da realidade pela porta do sonho e se deitam a correr atrás
da fantasia.
Os vélhos livros contam histórias encantadas e escândalos sem
par; sabem cousas que são o encanto dos vélhos e o
deslumbramento dos novos. Oh! se vós soubésseis cousas que
andam em vélhos livros?!...
Criaturas há que nem saudades teem. Saudades de quê? Nem
saudades, nem queixas, nem esperanças. Tudo se lhes foi diluindo
dia a dia. A miséria não deixa saudade: pode deixar lembrança.
Deixa às vezes no esqueleto, no macerado das faces, na pele por
colorir, sinais indeléveis da sua passagem. De resto, todos os seus
dias são iguais. As suas noites parecem medidas pelo mesmo
compasso. O ontem foi amargo, o hoje é tão amargo como o ontem.
Olhando em roda, ninguêm. E em verdade, um ninguêm é sempre
só, e não vale uma unidade um bilião de zeros. Se a criatura vive a
vida bruta de animal, a sua única felicidade é êsse covil—o sono—
onde as necessidades todos os dias a vão espancar, até um belo
dia dele não voltar mais. É por isso até que chamam ao sono irmão
da morte, como a Bíblia, ou primo, como o nosso Eça de Queiroz.

You might also like