diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:43:23 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:43:23 -0500 |
commit | 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 (patch) | |
tree | a9ef8ac1e1b8fe4207b6d64d3841bfb8990b6fd0 /files/uk/learn/server-side | |
parent | 074785cea106179cb3305637055ab0a009ca74f2 (diff) | |
download | translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.gz translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.bz2 translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.zip |
initial commit
Diffstat (limited to 'files/uk/learn/server-side')
-rw-r--r-- | files/uk/learn/server-side/django/index.html | 60 | ||||
-rw-r--r-- | files/uk/learn/server-side/django/introduction/index.html | 285 | ||||
-rw-r--r-- | files/uk/learn/server-side/express_nodejs/index.html | 77 | ||||
-rw-r--r-- | files/uk/learn/server-side/express_nodejs/routes/index.html | 644 | ||||
-rw-r--r-- | files/uk/learn/server-side/index.html | 52 |
5 files changed, 1118 insertions, 0 deletions
diff --git a/files/uk/learn/server-side/django/index.html b/files/uk/learn/server-side/django/index.html new file mode 100644 index 0000000000..c26c8fbe6b --- /dev/null +++ b/files/uk/learn/server-side/django/index.html @@ -0,0 +1,60 @@ +--- +title: Django веб-фреймворк (Python) +slug: Learn/Server-side/Django +translation_of: Learn/Server-side/Django +--- +<div>{{LearnSidebar}}</div> + +<p>Django є надзвичайно популярним і повнофункціональним серверним веб-фреймворком, що написаний на Python. Даний модуль показує вам, чому Django є одним з найпопулярніших структур веб-сервера, а також як налаштувати середовище розробки, і як приступити до роботи щоб створювати власні веб-додатки.</p> + +<h2 id="Передумови">Передумови</h2> + +<p>Перед початком цього модуля вам не потрібно володіти будь-якими знаннями про Django. Ви повинні лише розуміти, що таке серверне веб-програмування та веб-фреймворк, для цього читайте тему в нашому модулі - <a href="/en-US/docs/Learn/Server-side/First_steps">Програмування веб-сайту на стороні сервера, перші кроки</a>.</p> + +<p>Вітається володіння загальними знаннями концепцій програмування і мови програмування <a href="/en-US/docs/Glossary/Python">Python</a>, проте не є необхідним для розуміння основних понять.</p> + +<div class="note"> +<p><strong>Примітка</strong>: Python є однією із найпростіших мов програмування, легкою для освоєння та розуміння початківцями. Якщо ж ви прагнете зрозуміти цей модуль краще, то для цього є безліч безкоштовних книг і посібників, які є в інтернеті у вільному доступі (початківці у програмуванні можуть переглянути сторінку на wiki.python.org - <a href="https://wiki.python.org/moin/BeginnersGuide/NonProgrammers">Python для початківців</a>).</p> +</div> + +<h2 id="Посібники">Посібники</h2> + +<dl> + <dt><a href="/en-US/docs/Learn/Server-side/Django/Introduction">Вступ до Django</a></dt> + <dd>У цій першій статті про Django ми відповімо на питання "Що таке Django?" і дамо уявлення того що робить веб-фраймворк особливого. We'll outline the main features, including some of the advanced functionality that we won't have time to cover in detail in this module. We'll also show you some of the main building blocks of a Django application, to give you an idea of what it can do before you then go on to set it up and start playing.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/development_environment">Налаштування середовища розробки Django</a></dt> + <dd>Now that you know what Django is for, we'll show you how to setup and test a Django development environment on Windows, Linux (Ubuntu), and Mac OS X — whatever common operating system you are using, this article should give you what you need to be able to start developing Django apps.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website">Посібник Django: "Локальна бібліотека" - приклад веб-сайту</a></dt> + <dd>The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/skeleton_website">Посібник Django, частина 2: Створення скелету веб-сайту</a></dt> + <dd>This article shows how you can create a "skeleton" website project as a basis, which you can then go on to populate with site-specific settings, urls, models, views, and templates.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/Models">Посібник Django, частина 3: Використання моделей</a></dt> + <dd>This article shows how to define models for the <em>LocalLibrary</em> website — models represent the data structures we want to store our app's data in, and also allow Django to store data in a database for us (and modify it later on). It explains what a model is, how it is declared, and some of the main field types. It also briefly shows a few of the main ways you can access model data.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/Admin_site">Посібник Django, частина 4: Адміністрування сайту</a></dt> + <dd>Now that we've created models for the <em>LocalLibrary </em>website, we'll use the Django Admin site to add some "real" book data. First we'll show you how to register the models with the admin site, then we'll show you how to login and create some data. At the end we show some of ways you can further improve the presentation of the admin site.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/Home_page">Посібник Django, частина 5: Створення домашньої сторінки</a></dt> + <dd>We're now ready to add the code to display our first full page — a home page for the <em>LocalLibrary</em> that shows how many records we have of each model type and provides sidebar navigation links to our other pages. Along the way we'll gain practical experience in writing basic URL maps and views, getting records from the database, and using templates.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/Generic_views">Посібник Django Tutorial Part 6: Загальний список і детальний перегляд</a></dt> + <dd>This tutorial extends our <em>LocalLibrary</em> website, adding list and detail pages for books and authors. Here we'll learn about generic class-based views, and show how they can reduce the amount of code you have to write for common use cases. We'll also go into URL handling in greater detail, showing how to perform basic pattern matching.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/Sessions">Посібник Django, частина 7: Фреймворк сесій</a></dt> + <dd>This tutorial extends our <em>LocalLibrary</em> website, adding a session-based visit-counter to the home page. This is a relatively simple example, but it does shows how you can use the session framework to provide peristent behaviour for anonymous users in your own sites.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/Authentication">Посібник Django, частина 8: Аутентифікація користувачів і права доступу</a></dt> + <dd>In this tutorial we'll show you how to allow users to login to your site with their own accounts, and how to control what they can do and see based on whether or not they are logged in and their <em>permissions</em>. As part of this demonstration we'll extend the <em>LocalLibrary</em> website, adding login and logout pages, and user- and staff-specific pages for viewing books that have been borrowed.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/Forms">Посібник Django, частина 9: Робота з формами</a></dt> + <dd>In this tutorial we'll show you how to work with <a href="/en-US/docs/Web/Guide/HTML/Forms">HTML Forms</a> in Django, and in particular the easiest way to write forms to create, update, and delete model instances. As part of this demonstration we'll extend the <em>LocalLibrary</em> website so that librarians can renew books, and create, update, and delete authors using our own forms (rather than using the admin application).</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/Testing">Посібник Django, частина 10: Тестування веб-додатку Django</a></dt> + <dd>As websites grow they become harder to test manually — not only is there more to test, but, as the interactions between components become more complex, a small change in one area can require many additional tests to verify its impact on other areas. One way to mitigate these problems is to write automated tests, which can easily and reliably be run every time you make a change. This tutorial shows how to automate <em>unit testing</em> of your website using Django's test framework.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/Deployment">Посібник Django, частина 11: Розгортання веб-додатку Django на веб-сервері</a></dt> + <dd>Now you've created (and tested) an awesome <em>LocalLibrary</em> website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django/web_application_security">Django безпека веб-додатків</a></dt> + <dd>Protecting user data is an essential part of any website design. We previously explained some of the more common security threats in the article <a href="https://developer.mozilla.org/en-US/docs/Web/Security">Web security</a> — this article provides a practical demonstration of how Django's in-built protections handle such threats.</dd> +</dl> + +<h2 id="Оцінювання">Оцінювання</h2> + +<p>The following assessment will test your understanding of how to create a website using Django, as described in the guides listed above.</p> + +<dl> + <dt><a href="/en-US/docs/Learn/Server-side/Django/django_assessment_blog">DIY Django міні блог</a></dt> + <dd>In this assessment you'll use some of the knowledge you've learned from this module to create your own blog.</dd> +</dl> diff --git a/files/uk/learn/server-side/django/introduction/index.html b/files/uk/learn/server-side/django/introduction/index.html new file mode 100644 index 0000000000..26ef60a53a --- /dev/null +++ b/files/uk/learn/server-side/django/introduction/index.html @@ -0,0 +1,285 @@ +--- +title: Введення в Django +slug: Learn/Server-side/Django/Introduction +tags: + - CodingScripting + - Intro + - Learn + - Python + - Server-side programming + - django + - Джанго + - Кодування + - Програмування + - Пітон + - уроки +translation_of: Learn/Server-side/Django/Introduction +--- +<div>{{LearnSidebar}}</div> + +<div>{{NextMenu("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django")}}</div> + +<p class="summary">У цій першій статті Django, ми відповімо на питання "Що таке Django?" і даємо вам обзор того, що робить цей веб-фреймворк особливим. Ми розглянемо основні характеристики, включаючи деякі додаткові функціональні можливості модуля, які ми не встигли ще обговорити. Ми також покажемо вам деякі з основних блоків програми Django (хоча на даний момент у вас ще немає середовища розробки, в якій можна було б її протестувати).</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Передумови::</th> + <td>Basic computer literacy. A general understanding of <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/First_steps">server-side website programming</a>, and in particular the mechanics of <a href="/en-US/docs/Learn/Server-side/First_steps/Client-Server_overview">client-server interactions in websites</a>.</td> + </tr> + <tr> + <th scope="row">Завдання:</th> + <td>To gain familiarity with what Django is, what functionality it provides, and the main building blocks of a Django application.</td> + </tr> + </tbody> +</table> + +<h2 id="Що_таке_Django">Що таке Django?</h2> + +<p>Django - це високорівневий веб-фреймворк Python, що дозволяє швидко розвивати безпечні та підтримувані сайти. Побудований досвідченими розробниками, Django піклується про більшу частину турбот про веб-розробку, тому ви можете зосередитися на написанні програми без необхідності винаходити колесо.Це вільний і відкритий код, має процвітаюче і активне співтовариство, велику документацію, і безліч варіантів для безкоштовної і платної підтримки.</p> + +<p>Django допоможе вам написати програмне забезпечення, яке:</p> + +<dl> + <dt>Complete</dt> + <dd>Django слідує філософії "Батарейки включені" і забезпечує майже все, що розробники можуть захотіти зробити "з коробки". Оскільки все, що вам потрібно, є частиною одного "продукту", все працює безперешкодно, слідує послідовним принципам дизайну і має велику й найновішу документацію.</dd> + <dt>Універсальний</dt> + <dd>Django використовується для створення майже будь-якого типу веб-сайту — fвід систем управління контентом та вікі, через соціальні мережі та сайти новин. Він може працювати з будь-якою стороною клієнта, і може надавати вміст практично в будь-якому форматі (у тому числі HTML, RSS feeds, JSON, XML, etc). Сайт, який ви зараз читаєте, заснований на Django! <br> + Internally, while it provides choices for almost any functionality you might want (e.g. several popular databases, templating engines, etc.), it can also be extended to use other components if needed.</dd> + <dt>Безпечний</dt> + <dd>Django helps developers avoid many common security mistakes by providing a framework that has been engineered to "do the right things" to protect the website automatically. For example, Django provides a secure way to manage user accounts and passwords, avoiding common mistakes like putting session information in cookies where it is vulnerable (instead cookies just contain a key, and the actual data is stored in the database) or directly storing passwords rather than a password hash.<br> + <br> + <em>A password hash is a fixed-length value created by sending the password through a <a href="https://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>. Django can check if an entered password is correct by running it through the hash function and comparing the output to the stored hash value. However due to the "one-way" nature of the function, even if a stored hash value is compromised it is hard for an attacker to work out the original password.</em><br> + <br> + Django enables protection against many vulnerabilities by default, including SQL injection, cross-site scripting, cross-site request forgery and clickjacking (see <a href="/en-US/docs/Learn/Server-side/First_steps/Website_security">Website security</a> for more details of such attacks).</dd> + <dt>Масштабованість</dt> + <dd>Django uses a component-based “<a href="https://en.wikipedia.org/wiki/Shared_nothing_architecture">shared-nothing</a>” architecture (each part of the architecture is independent of the others, and can hence be replaced or changed if needed). Having a clear separation between the different parts means that it can scale for increased traffic by adding hardware at any level: caching servers, database servers, or application servers. Some of the busiest sites have successfully scaled Django to meet their demands (e.g. Instagram and Disqus, to name just two).</dd> + <dt>Підтримується</dt> + <dd>Django code is written using design principles and patterns that encourage the creation of maintainable and reusable code. In particular, it makes use of the Don't Repeat Yourself (DRY) principle so there is no unnecessary duplication, reducing the amount of code. Django also promotes the grouping of related functionality into reusable "applications" and, at a lower level, groups related code into modules (along the lines of the <a href="/en-US/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture">Model View Controller (MVC)</a> pattern).</dd> + <dt>Портативний</dt> + <dd>Django is written in Python, which runs on many platforms. That means that you are not tied to any particular server platform, and can run your applications on many flavours of Linux, Windows, and Mac OS X. Furthermore, Django is well-supported by many web hosting providers, who often provide specific infrastructure and documentation for hosting Django sites.</dd> +</dl> + +<h2 id="Звідки_він">Звідки він?</h2> + +<p>Django was initially developed between 2003 and 2005 by a web team who were responsible for creating and maintaining newspaper websites. After creating a number of sites, the team began to factor out and reuse lots of common code and design patterns. This common code evolved into a generic web development framework, which was open-sourced as the "Django" project in July 2005. </p> + +<p>Django has continued to grow and improve, from its first milestone release (1.0) in September 2008 through to the recently-released version 2.0 (2017). Each release has added new functionality and bug fixes, ranging from support for new types of databases, template engines, and caching, through to the addition of "generic" view functions and classes (which reduce the amount of code that developers have to write for a number of programming tasks). </p> + +<div class="note"> +<p><strong>Note</strong>: Check out <span style="line-height: 1.5;">the <a href="https://docs.djangoproject.com/en/stable/releases/">release notes</a> on the Django website to see what has changed in recent versions, and how much work is going into making Django better.</span></p> +</div> + +<p>Django is now a thriving, collaborative open source project, with many thousands of users and contributors. While it does still have some features that reflect its origin<span style="line-height: 1.5;">, Django has evolved into a versatile framework that is capable of developing any type of website. </span></p> + +<h2 id="Наскільки_популярним_є_Django">Наскільки популярним є Django?</h2> + +<p>There isn't any readily-available and definitive measurement of popularity of server-side frameworks (although sites like <a href="http://hotframeworks.com/">Hot Frameworks</a> attempt to assess popularity using mechanisms like counting the number of GitHub projects and StackOverflow questions for each platform). A better question is whether Django is "popular enough" to avoid the problems of unpopular platforms. Is it continuing to evolve? Can you get help if you need it? Is there an opportunity for you to get paid work if you learn Django? </p> + +<p>Based on the number of high profile sites that use Django, the number of people contributing to the codebase, and the number of people providing both free and paid for support, then yes, Django is a popular framework!</p> + +<p>High-profile sites that use Django include: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic, Open Knowledge Foundation, Pinterest, and Open Stack (source: <a href="https://www.djangoproject.com/">Django home page</a>).</p> + +<h2 id="Is_Django_opinionated">Is Django opinionated?</h2> + +<p>Web frameworks often refer to themselves as "opinionated" or "unopinionated".</p> + +<p>Opinionated frameworks are those with opinions about the "right way" to handle any particular task. They often support rapid development <em>in a particular domain </em>(solving problems of a particular type) because the right way to do anything is usually well-understood and well-documented. However they can be less flexible at solving problems outside their main domain, and tend to offer fewer choices for what components and approaches they can use.</p> + +<p>Unopinionated frameworks, by contrast, have far fewer restrictions on the best way to glue components together to achieve a goal, or even what components should be used. They make it easier for developers to use the most suitable tools to complete a particular task, albeit at the cost that you need to find those components yourself.<br> + <br> + Django is "somewhat opinionated", and hence delivers the "best of both worlds". It provides a set of components to handle most web development tasks and one (or two) preferred ways to use them. However, Django's decoupled architecture means that you can usually pick and choose from a number of different options, or add support for completely new ones if desired.</p> + +<h2 id="Як_виглядає_код_Django">Як виглядає код Django?</h2> + +<p>In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what is needed based on the URL and possibly information in <code>POST</code> data or <code>GET</code> data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.</p> + +<p>Django web applications typically group the code that handles each of these steps into separate files:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13931/basic-django.png" style="border-style: solid; border-width: 1px; display: block; margin: 0px auto;"></p> + +<ul> + <li><strong>URLs: </strong>While it is possible to process requests from every single URL via a single function, it is much more maintainable to write a separate view function to handle each resource. A URL mapper is used to redirect HTTP requests to the appropriate view based on the request URL. The URL mapper can also match particular patterns of strings or digits that appear in an URL, and pass these to a view function as data.</li> + <li><strong>View:</strong> A view is a request handler function, which receives HTTP requests and returns HTTP responses. Views access the data needed to satisfy requests via <em>models</em>, and delegate the formatting of the response to <em>templates</em>.</li> + <li><strong>Models:</strong> Models are Python objects that define the structure of an application's data, and provide mechanisms to manage (add, modify, delete) and query records in the database. </li> + <li><strong>Templates:</strong> A template is a text file defining the structure or layout of a file (such as an HTML page), with placeholders used to represent actual content. A <em>view</em> can dynamically create an HTML page using an HTML template, populating it with data from a <em>model</em>. A template can be used to define the structure of any type of file; it doesn't have to be HTML!</li> +</ul> + +<div class="note"> +<p><strong>Note</strong>: Django refers to this organisation as the "Model View Template (MVT)" architecture. It has many similarities to the more familiar <a href="/en-US/docs/Web/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture">Model View Controller</a> architecture. </p> +</div> + +<ul> +</ul> + +<p>The sections below will give you an idea of what these main parts of a Django app look like (we'll go into more detail later on in the course, once we've set up a development environment).</p> + +<h3 id="Sending_the_request_to_the_right_view_(urls.py)">Sending the request to the right view (urls.py)</h3> + +<p>A URL mapper is typically stored in a file named <strong>urls.py</strong>. In the example below, the mapper (<code>urlpatterns</code>) defines a list of mappings between <em>routes</em> (specific URL <em>patterns) </em>and corresponding view functions. If an HTTP Request is received that has a URL matching a specified pattern then the associated view function will be called and passed the request.</p> + +<pre>urlpatterns = [ + <strong>path('admin/', admin.site.urls), + </strong>path('book/<int:id>/', views.book_detail, name='book_detail'), + path('catalog/', include('catalog.urls')), + re_path(r'^([0-9]+)/$', views.best), +] +</pre> + +<p>The <code>urlpatterns</code> object is a list of <code>path()</code> and/or <code>re_path()</code> functions (Python lists are defined using square brackets, where items are separated by commas and may have an <a href="https://docs.python.org/3/faq/design.html#why-does-python-allow-commas-at-the-end-of-lists-and-tuples">optional trailing comma</a>. For example: <code>[item1, item2, item3,]</code>).</p> + +<p>The first argument to both methods is a route (pattern) that will be matched. The <code>path()</code> method uses angle brackets to define parts of a URL that will be captured and passed through to the view function as named arguments. The <code>re_path()</code> function uses a flexible pattern matching approach known as a regular expression. We'll talk about these in a later article!</p> + +<p>The second argument is another function that will be called when the pattern is matched. The notation <code>views.book_detail</code> indicates that the function is called <code>book_detail()</code> and can be found in a module called <code>views</code> (i.e. inside a file named <code>views.py</code>)</p> + +<h3 id="Handling_the_request_(views.py)">Handling the request (views.py)</h3> + +<p>Views are the heart of the web application, receiving HTTP requests from web clients and returning HTTP responses. In between, they marshall the other resources of the framework to access databases, render templates, etc. </p> + +<p>The example below shows a minimal view function <code>index()</code>, which could have been called by our URL mapper in the previous section. Like all view functions it receives an <code>HttpRequest</code> object as a parameter (<code>request</code>) and returns an <code>HttpResponse</code> object. In this case we don't do anything with the request, and our response simply returns a hard-coded string. We'll show you a request that does something more interesting in a later section.</p> + +<pre class="brush: python"># filename: views.py (Django view functions) + +from django.http import HttpResponse + +def index(request): + # Get an HttpRequest - the request parameter + # perform operations using information from the request. + # Return HttpResponse + return HttpResponse('Hello from Django!') +</pre> + +<div class="note"> +<p><strong>Note</strong>: A little bit of Python:</p> + +<ul> + <li><a href="https://docs.python.org/3/tutorial/modules.html">Python modules</a> are "libraries" of functions, stored in separate files, that we might want to use in our code. Here we import just the <code>HttpResponse</code> object from the <code>django.http</code> module so that we can use it in our view: <code>from django.http import HttpResponse</code> . There are other ways of importing some or all objects from a module.</li> + <li>Functions are declared using the <code>def</code> keyword as shown above, with named parameters listed in brackets after the name of the function; the whole line ends in a colon. Note how the next lines are all <strong>indented</strong>. The indentation is important, as it specifies that the lines of code are inside that particular block (mandatory indentation is a key feature of Python, and is one reason that Python code is so easy to read).</li> +</ul> +</div> + +<ul> +</ul> + +<p>Views are usually stored in a file called <strong>views.py</strong>.</p> + +<h3 id="Defining_data_models_(models.py)">Defining data models (models.py)</h3> + +<p>Django web applications manage and query data through Python objects referred to as models. Models define the structure of stored data, including the field <em>types</em> and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc. The definition of the model is independent of the underlying database — you can choose one of several as part of your project settings. Once you've chosen what database you want to use, you don't need to talk to it directly at all — you just write your model structure and other code, and Django handles all the dirty work of communicating with the database for you.</p> + +<p>The code snippet below shows a very simple Django model for a <code>Team</code> object. The <code>Team</code> class is derived from the django class <code>models.Model</code>. It defines the team name and team level as character fields and specifies a maximum number of characters to be stored for each record. The <code>team_level</code> can be one of several values, so we define it as a choice field and provide a mapping between choices to be displayed and data to be stored, along with a default value. </p> + +<pre class="brush: python"># filename: models.py + +from django.db import models + +class Team(models.Model): + team_name = models.CharField(max_length=40) + + TEAM_LEVELS = ( + ('U09', 'Under 09s'), + ('U10', 'Under 10s'), + ('U11', 'Under 11s'), + ... #list other team levels + ) + team_level = models.CharField(max_length=3, choices=TEAM_LEVELS, default='U11') +</pre> + +<div class="note"> +<p><strong>Note</strong>: A little bit of Python:</p> + +<ul> + <li>Python supports "object-oriented programming", a style of programming where we organise our code into objects, which include related data and functions for operating on that data. Objects can also inherit/extend/derive from other objects, allowing common behaviour between related objects to be shared. In Python we use the keyword <code>class</code> to define the "blueprint" for an object. We can create multiple specific <em>instances</em> of the type of object based on the model in the class.<br> + <br> + So for example, here we have a <code>Team</code> class, which derives from the <code>Model</code> class. This means it is a model, and will contain all the methods of a model, but we can also give it specialized features of its own too. In our model we define the fields our database will need to store our data, giving them specific names. Django uses these definitions, including the field names, to create the underlying database.</li> +</ul> +</div> + +<h3 id="Querying_data_(views.py)">Querying data (views.py)</h3> + +<p>The Django model provides a simple query API for searching the database. This can match against a number of fields at a time using different criteria (e.g. exact, case-insensitive, greater than, etc.), and can support complex statements (for example, you can specify a search on U11 teams that have a team name that starts with "Fr" or ends with "al"). </p> + +<p>The code snippet shows a view function (resource handler) for displaying all of our U09 teams. The line in bold shows how we can use the model query API to filter for all records where the <code>team_level</code> field has exactly the text 'U09' (note how this criteria is passed to the <code>filter()</code> function as an argument with the field name and match type separated by a double underscore: <strong>team_level__exact</strong>).</p> + +<pre class="brush: python">## filename: views.py + +from django.shortcuts import render +from .models import Team + +def index(request): + <strong>list_teams = Team.objects.filter(team_level__exact="U09")</strong> + context = {'youngest_teams': list_teams} + return render(request, '/best/index.html', context) +</pre> + +<dl> +</dl> + +<p>This function uses the <code>render()</code> function to create the <code>HttpResponse</code> that is sent back to the browser. This function is a <em>shortcut</em>; it creates an HTML file by combining a specified HTML template and some data to insert in the template (provided in the variable named "<code>context</code>"). In the next section we show how the template has the data inserted in it to create the HTML.</p> + +<h3 id="Rendering_data_(HTML_templates)">Rendering data (HTML templates)</h3> + +<p>Template systems allow you to specify the structure of an output document, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of document. Django supports both its native templating system and another popular Python library called Jinja2 out of the box (it can also be made to support other systems if needed). </p> + +<p>The code snippet shows what the HTML template called by the <code>render()</code> function in the previous section might look like. This template has been written under the assumption that it will have access to a list variable called <code>youngest_teams</code> when it is rendered (contained in the <code>context</code> variable inside the <code>render()</code> function above). Inside the HTML skeleton we have an expression that first checks if the <code>youngest_teams</code> variable exists, and then iterates it in a <code>for</code> loop. On each iteration the template displays each team's <code>team_name</code> value in an {{htmlelement("li")}} element.</p> + +<pre class="brush: python">## filename: best/templates/best/index.html + +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>Home page</title> +</head> +<body> + {% if youngest_teams %} + <ul> + {% for team in youngest_teams %} + <li>\{\{ team.team_name \}\}</li> + {% endfor %} + </ul> + {% else %} + <p>No teams are available.</p> + {% endif %} +</body> +</html></pre> + +<h2 id="What_else_can_you_do">What else can you do?</h2> + +<p>The preceding sections show the main features that you'll use in almost every web application: URL mapping, views, models and templates. Just a few of the other things provided by Django include:</p> + +<ul> + <li><strong>Forms</strong>: HTML Forms are used to collect user data for processing on the server. Django simplifies form creation, validation, and processing.</li> + <li><strong>User authentication and permissions</strong>: Django includes a robust user authentication and permission system that has been built with security in mind. </li> + <li><strong>Caching</strong>: Creating content dynamically is much more computationally intensive (and slow) than serving static content. Django provides flexible caching so that you can store all or part of a rendered page so that it doesn't get re-rendered except when necessary.</li> + <li><strong>Administration site</strong>: The Django administration site is included by default when you create an app using the basic skeleton. It makes it trivially easy to provide an admin page for site administrators to create, edit, and view any data models in your site.</li> + <li><strong>Serialising data</strong>: Django makes it easy to serialise and serve your data as XML or JSON. This can be useful when creating a web service (a website that purely serves data to be consumed by other applications or sites, and doesn't display anything itself), or when creating a website in which the client-side code handles all the rendering of data.</li> +</ul> + +<h2 id="Summary">Summary</h2> + +<p>Congratulations, you've completed the first step in your Django journey! You should now understand Django's main benefits, a little about its history, and roughly what each of the main parts of a Django app might look like. You should have also learned a few things about the Python programming language, including the syntax for lists, functions, and classes.</p> + +<p>You've already seen some real Django code above, but unlike with client-side code, you need to set up a development environment to run it. That's our next step.</p> + +<div>{{NextMenu("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django")}}</div> + +<h2 id="У_цьому_модулі">У цьому модулі</h2> + +<ul> + <li><a href="/en-US/docs/Learn/Server-side/Django/Introduction">Django introduction</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/development_environment">Setting up a Django development environment</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website">Django Tutorial: The Local Library website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/skeleton_website">Django Tutorial Part 2: Creating a skeleton website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/Models">Django Tutorial Part 3: Using models</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/Admin_site">Django Tutorial Part 4: Django admin site</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/Home_page">Django Tutorial Part 5: Creating our home page</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/Generic_views">Django Tutorial Part 6: Generic list and detail views</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/Sessions">Django Tutorial Part 7: Sessions framework</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/Authentication">Django Tutorial Part 8: User authentication and permissions</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/Forms">Django Tutorial Part 9: Working with forms</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/Testing">Django Tutorial Part 10: Testing a Django web application</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/Deployment">Django Tutorial Part 11: Deploying Django to production</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/web_application_security">Django web application security</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Django/django_assessment_blog">DIY Django mini blog</a></li> +</ul> diff --git a/files/uk/learn/server-side/express_nodejs/index.html b/files/uk/learn/server-side/express_nodejs/index.html new file mode 100644 index 0000000000..968f3e40e2 --- /dev/null +++ b/files/uk/learn/server-side/express_nodejs/index.html @@ -0,0 +1,77 @@ +--- +title: Express web framework (Node.js/JavaScript) +slug: Learn/Server-side/Express_Nodejs +tags: + - Beginner + - CodingScripting + - Express + - Express.js + - Intro + - JavaScript + - Learn + - NeedsTranslation + - Node + - Server-side programming + - TopicStub + - node.js +translation_of: Learn/Server-side/Express_Nodejs +--- +<div>{{LearnSidebar}}</div> + +<p class="summary">Express is a popular unopinionated web framework, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.</p> + +<h2 id="Prerequisites">Prerequisites</h2> + +<p>Before starting this module you will need to understand what server-side web programming and web frameworks are, ideally by reading the topics in our <a href="/en-US/docs/Learn/Server-side/First_steps">Server-side website programming first steps</a> module. A general knowledge of programming concepts and <a href="/en-US/docs/Web/JavaScript">JavaScript</a> is highly recommended, but not essential to understanding the core concepts.</p> + +<div class="note"> +<p><strong>Note</strong>: This website has many useful resources for learning JavaScript<em> in the context of client-side development</em>: <a href="/en-US/docs/Web/JavaScript">JavaScript</a>, <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript Guide</a>, <a href="/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics">JavaScript Basics</a>, <a href="/en-US/docs/Learn/JavaScript">JavaScript</a> (learning). The core JavaScript language and concepts are the same for server-side development on Node.js and this material will be relevant. Node.js offers <a href="https://nodejs.org/dist/latest-v6.x/docs/api/">additional APIs</a> for supporting functionality that is useful in browserless environments, e.g. to create HTTP servers and access the file system, but does not support JavaScript APIs for working with the browser and DOM.</p> + +<p>This guide will provide some information about working with Node.js and Express, and there are numerous other excellent resources on the Internet and in books — some of these linked from <a href="http://stackoverflow.com/a/5511507/894359">How do I get started with Node.js</a> (StackOverflow) and <a href="https://www.quora.com/What-are-the-best-resources-for-learning-Node-js?">What are the best resources for learning Node.js?</a> (Quora).</p> +</div> + +<h2 id="Guides">Guides</h2> + +<dl> + <dt><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></dt> + <dd>In this first Express article we answer the questions "What is Node?" and "What is Express?" and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></dt> + <dd>Now that you know what Express is for, we'll show you how to set up and test a Node/Express development environment on Windows, Linux (Ubuntu), and Mac OS X. Whatever common operating system you are using, this article should give you what you need to be able to start developing Express apps.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></dt> + <dd>The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></dt> + <dd>This article shows how you can create a "skeleton" website project, which you can then go on to populate with site-specific routes, templates/views, and databases.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></dt> + <dd>This article briefly introduces databases for Node/Express. It then goes on to show how we can use <a href="http://mongoosejs.com/">Mongoose</a> to provide database access for the <em>LocalLibrary</em> website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways you can access model data.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></dt> + <dd>In this tutorial we'll set up routes (URL handling code) with "dummy" handler functions for all the resource endpoints that we'll eventually need in the <em>LocalLibrary</em> website. On completion, we'll have a modular structure for our route handling code, that we can extend with real handler functions in the following articles. We'll also have a really good understanding of how to create modular routes using Express.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></dt> + <dd>We're now ready to add the pages that display the <em>LocalLibrary</em> website books and other data. The pages will include a home page that shows how many records we have of each model type, and list and detail pages for all of our models. Along the way we'll gain practical experience in getting records from the database, and using templates.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></dt> + <dd>In this tutorial we'll show you how to work with <a href="/en-US/docs/Web/Guide/HTML/Forms">HTML Forms</a> in Express, using Pug, and in particular how to write forms to create, update, and delete documents from the database.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></dt> + <dd>Now you've created an awesome <em>LocalLibrary</em> website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.</dd> +</dl> + +<h2 id="See_also">See also</h2> + +<dl> + <dt><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Installing_on_PWS_Cloud_Foundry">Installing LocalLibrary on PWS/Cloud Foundry</a></dt> + <dd>This article provides a practical demonstration of how to install <em>LocalLibrary</em> on the <a href="http://run.pivotal.io">Pivotal Web Services PaaS cloud</a> — this is a full-featured, open source alternative to Heroku, the PaaS cloud service used in Part 7 of the tutorial, listed above. PWS/Cloud Foundry is definitely worth checking out if you are looking for an alternative to Heroku (or another PaaS cloud service), or simply feel like trying something different.</dd> +</dl> + +<h2 id="Adding_more_tutorials">Adding more tutorials</h2> + +<div> +<p>That's the end of the tutorial articles (for now). If you would like to extend it, other interesting topics to cover are:</p> + +<ul> + <li>Using sessions</li> + <li>User authentication</li> + <li>User authorisation and permissions</li> + <li>Testing an Express web application</li> + <li>Web security for Express web applications.</li> +</ul> + +<p>And of course it would be excellent to have an assessment task!</p> +</div> diff --git a/files/uk/learn/server-side/express_nodejs/routes/index.html b/files/uk/learn/server-side/express_nodejs/routes/index.html new file mode 100644 index 0000000000..9f9e704565 --- /dev/null +++ b/files/uk/learn/server-side/express_nodejs/routes/index.html @@ -0,0 +1,644 @@ +--- +title: 'Express Tutorial Part 4: Routes and controllers' +slug: Learn/Server-side/Express_Nodejs/routes +translation_of: Learn/Server-side/Express_Nodejs/routes +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs")}}</div> + +<p class="summary">У цій статті ми настроїмо (URL handling code) з "штучною" функцією обробки всіх можливих шляхів (endpoints) які потрібні у <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">LocalLibrary</a> сайті. У підсумку ми матимемо модульну структуру відладки для всіх шляхів, яку ми зможемо використати у наступній статті. Ми матимемо хороше розуміння, як створювати модульну структуру для шляхів які використовує Express!</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Передумови:</th> + <td>Прочитайте <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a>. Закінчіть попередні частини (включаючи <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a>).</td> + </tr> + <tr> + <th scope="row">Мета:</th> + <td>Вміти створити простий шляхи. Настроїти обробку всі URL шляхів.</td> + </tr> + </tbody> +</table> + +<h2 id="Overview">Overview</h2> + +<p>In the <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">last tutorial article</a> we defined <em>Mongoose</em> models to interact with the database, and used a (standalone) script to create some initial library records. We can now write the code to present that information to users. The first thing we need to do is determine what information we want to be able to display in our pages, and then define appropriate URLs for returning those resources. Then we're going to need to create the routes (URL handlers) and views (templates) to display those pages.</p> + +<p>The diagram below is provided as a reminder of the main flow of data and things that need to be implemented when handling an HTTP request/response. In addition to the views and routes the diagram shows "controllers" — functions that separate out the code to route requests from the code that actually processes requests.</p> + +<p>As we've already created the models, the main things we'll need to create are:</p> + +<ul> + <li>"Routes" to forward the supported requests (and any information encoded in request URLs) to the appropriate controller functions.</li> + <li>Controller functions to get the requested data from the models, create an HTML page displaying the data, and return it to the user to view in the browser.</li> + <li>Views (templates) used by the controllers to render the data.</li> +</ul> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14456/MVC%20Express.png" style="height: 460px; width: 800px;"></p> + +<p>Ultimately we might have pages to show lists and detail information for books, genres, authors and bookinstances, along with pages to create, update, and delete records. That's a lot to document in one article. Therefore most of this article will concentrate on setting up our routes and controllers to return "dummy" content. We'll extend the controller methods in our subsequent articles to work with model data.</p> + +<p>The first section below provides a brief "primer" on how to use the Express <a href="http://expressjs.com/en/4x/api.html#router">Router</a> middleware. We'll then use that knowledge in the following sections when we set up the LocalLibrary routes.</p> + +<h2 id="Routes_primer">Routes primer</h2> + +<p>A route is a section of Express code that associates an HTTP verb (<code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code>, etc.), an URL path/pattern, and a function that is called to handle that pattern.</p> + +<p>There are several ways to create routes. For this tutorial we're going to use the <code><a href="http://expressjs.com/en/guide/routing.html#express-router">express.Router</a></code> middleware as it allows us to group the route handlers for a particular part of a site together and access them using a common route-prefix. We'll keep all our library-related routes in a "catalog" module, and, if we add routes for handling user accounts or other functions, we can keep them grouped separately.</p> + +<div class="note"> +<p><strong>Note:</strong> We discussed Express application routes briefly in our <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction#Creating_route_handlers">Express Introduction > Creating route handlers</a>. Other than providing better support for modularization (as discussed in the first subsection below), using <em>Router</em> is very similar to defining routes directly on the <em>Express application object</em>.</p> +</div> + +<p>The rest of this section provides an overview of how the <code>Router</code> can be used to define the routes.</p> + +<h3 id="Defining_and_using_separate_route_modules">Defining and using separate route modules</h3> + +<p>The code below provides a concrete example of how we can create a route module and then use it in an <em>Express</em> application.</p> + +<p>First we create routes for a wiki in a module named <strong>wiki.js</strong>. The code first imports the Express application object, uses it to get a <code>Router</code> object and then adds a couple of routes to it using the <code>get()</code> method. Last of all the module exports the <code>Router</code> object.</p> + +<pre class="brush: js"><code>// wiki.js - Wiki route module. + +var express = require('express'); +var router = express.Router(); + +// Home page route. +router.get('/', function (req, res) { + res.send('Wiki home page'); +}) + +// About page route. +router.get('/about', function (req, res) { + res.send('About this wiki'); +}) + +module.exports = router;</code> + +</pre> + +<div class="note"> +<p><strong>Note:</strong> Above we are defining our route handler callbacks directly in the router functions. In the LocalLibrary we'll define these callbacks in a separate controller module.</p> +</div> + +<p>To use the router module in our main app file we first <code>require()</code> the route module (<strong>wiki.js</strong>). We then call <code>use()</code> on the <em>Express</em> application to add the Router to the middleware handling path, specifying an URL path of 'wiki'.</p> + +<pre class="brush: js"><code>var wiki = require('./wiki.js'); +// ... +app.use('/wiki', wiki);</code></pre> + +<p>The two routes defined in our wiki route module are then accessible from <code>/wiki/</code> and <code>/wiki/about/</code>.</p> + +<h3 id="Route_functions">Route functions</h3> + +<p>Our module above defines a couple of typical route functions. The "about" route (reproduced below) is defined using the <code>Router.get()</code> method, which responds only to HTTP GET requests. The first argument to this method is the URL path while the second is a callback function that will be invoked if an HTTP GET request with the path is received.</p> + +<pre class="brush: js"><code>router.get('/about', function (req, res) { + res.send('About this wiki'); +})</code> +</pre> + +<p>The callback takes three arguments (usually named as shown: <code>req</code>, <code>res</code>, <code>next</code>), that will contain the HTTP Request object, HTTP response, and the <em>next</em> function in the middleware chain.</p> + +<div class="note"> +<p><strong>Note:</strong> Router functions are <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction#Using_middleware">Express middleware</a>, which means that they must either complete (respond to) the request or call the <code>next</code> function in the chain. In the case above we complete the request using <code>send()</code>, so the <code>next</code> argument is not used (and we choose not to specify it).</p> + +<p>The router function above takes a single callback, but you can specify as many callback arguments as you want, or an array of callback functions. Each function is part of the middleware chain, and will be called in the order it is added to the chain (unless a preceding function completes the request).</p> +</div> + +<p>The callback function here calls <code><a href="https://expressjs.com/en/4x/api.html#res.send">send()</a></code> on the response to return the string "About this wiki" when we receive a GET request with the path ('<code>/about'</code>). There are a <a href="https://expressjs.com/en/guide/routing.html#response-methods">number of other response methods</a> for ending the request/response cycle. For example, you could call <code><a href="https://expressjs.com/en/4x/api.html#res.json">res.json()</a></code> to send a JSON response or <code><a href="https://expressjs.com/en/4x/api.html#res.sendFile">res.sendFile()</a></code> to send a file. The response method that we'll be using most often as we build up the library is <a href="https://expressjs.com/en/4x/api.html#res.render">render()</a>, which creates and returns HTML files using templates and data—we'll talk a lot more about that in a later article!</p> + +<h3 id="HTTP_verbs">HTTP verbs</h3> + +<p>The example routes above use the <code>Router.get()</code> method to respond to HTTP GET requests with a certain path.</p> + +<p>The <code>Router</code> also provides route methods for all the other HTTP verbs, that are mostly used in exactly the same way: <code>post()</code>, <code>put()</code>, <code>delete()</code>, <code>options()</code>, <code>trace()</code>, <code>copy()</code>, <code>lock()</code>, <code>mkcol()</code>, <code>move()</code>, <code>purge()</code>, <code>propfind()</code>, <code>proppatch()</code>, <code>unlock()</code>, <code>report()</code>, <code>mkactivity()</code>, <code>checkout()</code>, <code>merge()</code>, <code>m-</code><code>search()</code>, <code>notify()</code>, <code>subscribe()</code>, <code>unsubscribe()</code>, <code>patch()</code>, <code>search()</code>, and <code>connect()</code>.</p> + +<p>For example, the code below behaves just like the previous <code>/about</code> route, but only responds to HTTP POST requests.</p> + +<pre class="brush: js"><code>router.post('/about', function (req, res) { + res.send('About this wiki'); +})</code></pre> + +<h3 id="Route_paths">Route paths</h3> + +<p>The route paths define the endpoints at which requests can be made. The examples we've seen so far have just been strings, and are used exactly as written: '/', '/about', '/book', '/any-random.path'.</p> + +<p>Route paths can also be string patterns. String patterns use a subset of regular expression syntax to define <em>patterns</em> of endpoints that will be matched. The subset is listed below (note that the hyphen (<code>-</code>) and the dot (<code>.</code>) are interpreted literally by string-based paths):</p> + +<ul> + <li>? : The endpoint must have 0 or 1 of the preceding character. E.g. a route path of <code>'/ab?cd'</code> will match endpoints <code>acd</code> or <code>abcd</code>.</li> + <li>+ : The endpoint must have 1 or more of the preceding character. E.g. a route path of <code>'/ab+cd'</code> will match endpoints <code>abcd</code>, <code>abbcd</code>, <code>abbbcd</code>, and so on.</li> + <li>* : The endpoint may have an arbitrary string where the * character is placed. E.g. a route path of <code>'ab*cd'</code> will match endpoints <code>abcd</code>, <code>abXcd</code>, <code>abSOMErandomTEXTcd</code>, and so on.</li> + <li>() : Grouping match on a set of characters to perform another operation on. E.g. <code>'/ab(cd)?e'</code> will peform a ? match on (cd) —it will match <code>abe</code> and <code>abcde</code>.</li> +</ul> + +<p>The route paths can also be JavaScript <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">regular expressions</a>. For example, the route path below will match <code>catfish </code>and <code>dogfish</code>, but not <code>catflap</code>, <code>catfishhead</code>, and so on. Note that the path for a regular expression uses regular expression syntax (it is not a quoted string as in the previous cases).</p> + +<pre class="brush: js"><code>app.get(/.*fish$/, function (req, res) { + ... +})</code></pre> + +<div class="note"> +<p><strong>Note:</strong> Most of our routes for the LocalLibrary will simply use strings and not string patterns and regular expressions. We'll also use route parameters as discussed in the next section.</p> +</div> + +<h3 id="Route_parameters">Route parameters</h3> + +<p>Route parameters are <em>named URL segments</em> used to capture the values specified at their position in the URL. The named segments are prefixed with a colon and then the name (e.g. <code>/<strong>:</strong>your_parameter_name/</code>. The captured values are stored in the <code>req.params</code> object using the parameter names as keys (e.g. <code>req.params.your_parameter_name</code>).</p> + +<p>So for example, consider a URL encoded to contain information about users and books: <code>http://localhost:3000/users/34/books/8989</code>. We can extract this information as shown below, with the <code>userId</code> and <code>bookId</code> path parameters:</p> + +<pre><code>app.get('/users/:userId/books/:bookId', function (req, res) { + // Access userId via: req.params.userId + // Access bookId via: req.params.bookId + res.send(req.params); +}) +</code></pre> + +<p>The names of route parameters must be made up of “word characters” (A-Z, a-z, 0-9, and _).</p> + +<div class="note"> +<p><strong>Note:</strong> The URL <em>/book/create</em> will be matched by a route like <code>/book/:bookId</code> (which will extract a "bookId" value of '<code>create</code>'). The first route that matches an incoming URL will be used, so if you want to process <code>/book/create</code> URLs separately, their route handler must be defined before your <code>/book/:bookId</code> route.</p> +</div> + +<p>That's all you need to get started with routes - if needed you can find more information in the Express docs: <a href="http://expressjs.com/en/starter/basic-routing.html">Basic routing</a> and <a href="http://expressjs.com/en/guide/routing.html">Routing guide</a>. The following sections show how we'll set up our routes and controllers for the LocalLibrary.</p> + +<h2 id="Routes_needed_for_the_LocalLibrary">Routes needed for the LocalLibrary</h2> + +<p>The URLs that we're ultimately going to need for our pages are listed below, where <em>object</em> is replaced by the name of each of our models (book, bookinstance, genre, author), <em>objects</em> is the plural of object, and <em>id</em> is the unique instance field (<code>_id</code>) that is given to each Mongoose model instance by default.</p> + +<ul> + <li><code>catalog/</code> — The home/index page.</li> + <li><code>catalog/<objects>/</code> — The list of all books, bookinstances, genres, or authors (e.g. /<code>catalog/books/</code>, /<code>catalog/genres/</code>, etc.)</li> + <li><code>catalog/<object>/<em><id></em></code> — The detail page for a specific book, bookinstance, genre, or author with the given <code><em>_id</em></code> field value (e.g. <code>/catalog/book/584493c1f4887f06c0e67d37)</code>.</li> + <li><code>catalog/<object>/create</code> — The form to create a new book, bookinstance, genre, or author (e.g. <code>/catalog/book/create)</code>.</li> + <li><code>catalog/<object>/<em><id></em>/update</code> — The form to update a specific book, bookinstance, genre, or author with the given <code><em>_id</em></code> field value (e.g. <code>/catalog/book/584493c1f4887f06c0e67d37/update)</code>.</li> + <li><code>catalog/<object>/<em><id></em>/delete</code> — The form to delete a specific book, bookinstance, genre, author with the given <code><em>_id</em></code> field value (e.g. <code>/catalog/book/584493c1f4887f06c0e67d37/delete)</code>.</li> +</ul> + +<p>The first home page and list pages don't encode any additional information. While the results returned will depend on the model type and the content in the database, the queries run to get the information will always be the same (similarly the code run for object creation will always be similar).</p> + +<p>By contrast the other URLs are used to act on a specific document/model instance—these encode the identity of the item in the URL (shown as <code><em><id></em></code> above). We'll use path parameters to extract the encoded information and pass it to the route handler (and in a later article we'll use this to dynamically determine what information to get from the database). By encoding the information in our URL we only need one route for every resource of a particular type (e.g. one route to handle the display of every single book item).</p> + +<div class="note"> +<p><strong>Note</strong>: Express allows you to construct your URLs any way you like — you can encode information in the body of the URL as shown above or use URL <code>GET</code> parameters (e.g. <code>/book/?id=6</code>). Whichever approach you use, the URLs should be kept clean, logical and readable (<a href="https://www.w3.org/Provider/Style/URI">check out the W3C advice here</a>).</p> +</div> + +<p>Next we create our route handler callback functions and route code for all the above URLs.</p> + +<h2 id="Create_the_route-handler_callback_functions">Create the route-handler callback functions</h2> + +<p>Before we define our routes, we'll first create all the dummy/skeleton callback functions that they will invoke. The callbacks will be stored in separate "controller" modules for Books, BookInstances, Genres, and Authors (you can use any file/module structure, but this seems an appropriate granularity for this project).</p> + +<p>Start by creating a folder for our controllers in the project root (<strong>/controllers</strong>) and then create separate controller files/modules for handling each of the models:</p> + +<pre>/express-locallibrary-tutorial //the project root + <strong>/controllers</strong> + <strong>authorController.js</strong> + <strong>bookController.js</strong> + <strong>bookinstanceController.js</strong> + <strong>genreController.js</strong></pre> + +<h3 id="Author_controller">Author controller</h3> + +<p>Open the <strong>/controllers/authorController.js</strong> file and copy in the following code:</p> + +<pre class="brush: js">var Author = require('../models/author'); + +// Display list of all Authors. +exports.author_list = function(req, res) { + res.send('NOT IMPLEMENTED: Author list'); +}; + +// Display detail page for a specific Author. +exports.author_detail = function(req, res) { + res.send('NOT IMPLEMENTED: Author detail: ' + req.params.id); +}; + +// Display Author create form on GET. +exports.author_create_get = function(req, res) { + res.send('NOT IMPLEMENTED: Author create GET'); +}; + +// Handle Author create on POST. +exports.author_create_post = function(req, res) { + res.send('NOT IMPLEMENTED: Author create POST'); +}; + +// Display Author delete form on GET. +exports.author_delete_get = function(req, res) { + res.send('NOT IMPLEMENTED: Author delete GET'); +}; + +// Handle Author delete on POST. +exports.author_delete_post = function(req, res) { + res.send('NOT IMPLEMENTED: Author delete POST'); +}; + +// Display Author update form on GET. +exports.author_update_get = function(req, res) { + res.send('NOT IMPLEMENTED: Author update GET'); +}; + +// Handle Author update on POST. +exports.author_update_post = function(req, res) { + res.send('NOT IMPLEMENTED: Author update POST'); +}; +</pre> + +<p>The module first requires the model that we'll later be using to access and update our data. It then exports functions for each of the URLs we wish to handle (the create, update and delete operations use forms, and hence also have additional methods for handling form post requests — we'll discuss those methods in the "forms article" later on).</p> + +<p>All the functions have the standard form of an <em>Express middleware function</em>, with arguments for the request, response, and the <code>next</code> function to be called if the method does not complete the request cycle (in all these cases it does!). The methods simply return a string indicating that the associated page has not yet been created. If a controller function is expected to receive path parameters, these are output in the message string (see <code>req.params.id</code> above).</p> + +<h4 id="BookInstance_controller">BookInstance controller</h4> + +<p>Open the <strong>/controllers/bookinstanceController.js</strong> file and copy in the following code (this follows an identical pattern to the <code>Author</code> controller module):</p> + +<pre class="brush: js">var BookInstance = require('../models/bookinstance'); + +// Display list of all BookInstances. +exports.bookinstance_list = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance list'); +}; + +// Display detail page for a specific BookInstance. +exports.bookinstance_detail = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance detail: ' + req.params.id); +}; + +// Display BookInstance create form on GET. +exports.bookinstance_create_get = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance create GET'); +}; + +// Handle BookInstance create on POST. +exports.bookinstance_create_post = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance create POST'); +}; + +// Display BookInstance delete form on GET. +exports.bookinstance_delete_get = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance delete GET'); +}; + +// Handle BookInstance delete on POST. +exports.bookinstance_delete_post = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance delete POST'); +}; + +// Display BookInstance update form on GET. +exports.bookinstance_update_get = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance update GET'); +}; + +// Handle bookinstance update on POST. +exports.bookinstance_update_post = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance update POST'); +}; +</pre> + +<h4 id="Genre_controller">Genre controller</h4> + +<p>Open the <strong>/controllers/genreController.js</strong> file and copy in the following text (this follows an identical pattern to the <code>Author</code> and <code>BookInstance</code> files):</p> + +<pre class="brush: js">var Genre = require('../models/genre'); + +// Display list of all Genre. +exports.genre_list = function(req, res) { + res.send('NOT IMPLEMENTED: Genre list'); +}; + +// Display detail page for a specific Genre. +exports.genre_detail = function(req, res) { + res.send('NOT IMPLEMENTED: Genre detail: ' + req.params.id); +}; + +// Display Genre create form on GET. +exports.genre_create_get = function(req, res) { + res.send('NOT IMPLEMENTED: Genre create GET'); +}; + +// Handle Genre create on POST. +exports.genre_create_post = function(req, res) { + res.send('NOT IMPLEMENTED: Genre create POST'); +}; + +// Display Genre delete form on GET. +exports.genre_delete_get = function(req, res) { + res.send('NOT IMPLEMENTED: Genre delete GET'); +}; + +// Handle Genre delete on POST. +exports.genre_delete_post = function(req, res) { + res.send('NOT IMPLEMENTED: Genre delete POST'); +}; + +// Display Genre update form on GET. +exports.genre_update_get = function(req, res) { + res.send('NOT IMPLEMENTED: Genre update GET'); +}; + +// Handle Genre update on POST. +exports.genre_update_post = function(req, res) { + res.send('NOT IMPLEMENTED: Genre update POST'); +}; +</pre> + +<h4 id="Book_controller">Book controller</h4> + +<p>Open the <strong>/controllers/bookController.js</strong> file and copy in the following code. This follows the same pattern as the other controller modules, but additionally has an <code>index()</code> function for displaying the site welcome page:</p> + +<pre class="brush: js">var Book = require('../models/book'); + +<strong>exports.index = function(req, res) { + res.send('NOT IMPLEMENTED: Site Home Page'); +};</strong> + +// Display list of all books. +exports.book_list = function(req, res) { + res.send('NOT IMPLEMENTED: Book list'); +}; + +// Display detail page for a specific book. +exports.book_detail = function(req, res) { + res.send('NOT IMPLEMENTED: Book detail: ' + req.params.id); +}; + +// Display book create form on GET. +exports.book_create_get = function(req, res) { + res.send('NOT IMPLEMENTED: Book create GET'); +}; + +// Handle book create on POST. +exports.book_create_post = function(req, res) { + res.send('NOT IMPLEMENTED: Book create POST'); +}; + +// Display book delete form on GET. +exports.book_delete_get = function(req, res) { + res.send('NOT IMPLEMENTED: Book delete GET'); +}; + +// Handle book delete on POST. +exports.book_delete_post = function(req, res) { + res.send('NOT IMPLEMENTED: Book delete POST'); +}; + +// Display book update form on GET. +exports.book_update_get = function(req, res) { + res.send('NOT IMPLEMENTED: Book update GET'); +}; + +// Handle book update on POST. +exports.book_update_post = function(req, res) { + res.send('NOT IMPLEMENTED: Book update POST'); +}; +</pre> + +<h2 id="Create_the_catalog_route_module">Create the catalog route module</h2> + +<p>Next we create <em>routes</em> for all the URLs <a href="#local_libary_routes">needed by the LocalLibrary website</a>, which will call the controller functions we defined in the previous section.</p> + +<p>The skeleton already has a <strong>./routes</strong> folder containing routes for the <em>index</em> and <em>users</em>. Create another route file — <strong>catalog.js</strong> — inside this folder, as shown.</p> + +<pre>/express-locallibrary-tutorial //the project root + /routes + index.js + users.js + <strong>catalog.js</strong></pre> + +<p>Open <strong>/routes/</strong><strong>catalog.js</strong> and copy in the code below:</p> + +<pre class="brush: js"><strong>var express = require('express'); +var router = express.Router(); +</strong> +// Require controller modules. +var book_controller = require('../controllers/bookController'); +var author_controller = require('../controllers/authorController'); +var genre_controller = require('../controllers/genreController'); +var book_instance_controller = require('../controllers/bookinstanceController'); + +/// BOOK ROUTES /// + +// GET catalog home page. +router.get('/', book_controller.index); + +// GET request for creating a Book. NOTE This must come before routes that display Book (uses id). +router.get('/book/create', book_controller.book_create_get); + +// POST request for creating Book. +router.post('/book/create', book_controller.book_create_post); + +// GET request to delete Book. +router.get('/book/:id/delete', book_controller.book_delete_get); + +// POST request to delete Book. +router.post('/book/:id/delete', book_controller.book_delete_post); + +// GET request to update Book. +router.get('/book/:id/update', book_controller.book_update_get); + +// POST request to update Book. +router.post('/book/:id/update', book_controller.book_update_post); + +// GET request for one Book. +router.get('/book/:id', book_controller.book_detail); + +// GET request for list of all Book items. +router.get('/books', book_controller.book_list); + +/// AUTHOR ROUTES /// + +// GET request for creating Author. NOTE This must come before route for id (i.e. display author). +router.get('/author/create', author_controller.author_create_get); + +// POST request for creating Author. +router.post('/author/create', author_controller.author_create_post); + +// GET request to delete Author. +router.get('/author/:id/delete', author_controller.author_delete_get); + +// POST request to delete Author. +router.post('/author/:id/delete', author_controller.author_delete_post); + +// GET request to update Author. +router.get('/author/:id/update', author_controller.author_update_get); + +// POST request to update Author. +router.post('/author/:id/update', author_controller.author_update_post); + +// GET request for one Author. +router.get('/author/:id', author_controller.author_detail); + +// GET request for list of all Authors. +router.get('/authors', author_controller.author_list); + +/// GENRE ROUTES /// + +// GET request for creating a Genre. NOTE This must come before route that displays Genre (uses id). +router.get('/genre/create', genre_controller.genre_create_get); + +//POST request for creating Genre. +router.post('/genre/create', genre_controller.genre_create_post); + +// GET request to delete Genre. +router.get('/genre/:id/delete', genre_controller.genre_delete_get); + +// POST request to delete Genre. +router.post('/genre/:id/delete', genre_controller.genre_delete_post); + +// GET request to update Genre. +router.get('/genre/:id/update', genre_controller.genre_update_get); + +// POST request to update Genre. +router.post('/genre/:id/update', genre_controller.genre_update_post); + +// GET request for one Genre. +router.get('/genre/:id', genre_controller.genre_detail); + +// GET request for list of all Genre. +router.get('/genres', genre_controller.genre_list); + +/// BOOKINSTANCE ROUTES /// + +// GET request for creating a BookInstance. NOTE This must come before route that displays BookInstance (uses id). +router.get('/bookinstance/create', book_instance_controller.bookinstance_create_get); + +// POST request for creating BookInstance. +router.post('/bookinstance/create', book_instance_controller.bookinstance_create_post); + +// GET request to delete BookInstance. +router.get('/bookinstance/:id/delete', book_instance_controller.bookinstance_delete_get); + +// POST request to delete BookInstance. +router.post('/bookinstance/:id/delete', book_instance_controller.bookinstance_delete_post); + +// GET request to update BookInstance. +router.get('/bookinstance/:id/update', book_instance_controller.bookinstance_update_get); + +// POST request to update BookInstance. +router.post('/bookinstance/:id/update', book_instance_controller.bookinstance_update_post); + +// GET request for one BookInstance. +router.get('/bookinstance/:id', book_instance_controller.bookinstance_detail); + +// GET request for list of all BookInstance. +router.get('/bookinstances', book_instance_controller.bookinstance_list); + +<strong>module.exports = router;</strong> +</pre> + +<p>The module requires Express and then uses it to create a <code>Router</code> object. The routes are all set up on the router, which is then exported.</p> + +<p>The routes are defined either using <code>.get()</code> or <code>.post()</code> methods on the router object. All the paths are defined using strings (we don't use string patterns or regular expressions). Routes that act on some specific resource (e.g. book) use path parameters to get the object id from the URL.</p> + +<p>The handler functions are all imported from the controller modules we created in the previous section.</p> + +<h3 id="Update_the_index_route_module">Update the index route module</h3> + +<p>We've set up all our new routes, but we still have a route to the original page. Let's instead redirect this to the new index page that we've created at the path '/catalog'.</p> + +<p>Open <strong>/routes/index.js</strong> and replace the existing route with the function below.</p> + +<pre class="brush: js">// GET home page. +router.get('/', function(req, res) { + res.redirect('/catalog'); +});</pre> + +<div class="note"> +<p><strong>Note:</strong> This is our first use of the <a href="https://expressjs.com/en/4x/api.html#res.redirect">redirect()</a> response method. This redirects to the specified page, by default sending HTTP status code "302 Found". You can change the status code returned if needed, and supply either absolute or relative paths.</p> +</div> + +<h3 id="Update_app.js">Update app.js</h3> + +<p>The last step is to add the routes to the middleware chain. We do this in <code>app.js</code>.</p> + +<p>Open <strong>app.js</strong> and require the catalog route below the other routes (add the third line shown below, underneath the other two):</p> + +<pre class="brush: js">var index = require('./routes/index'); +var users = require('./routes/users'); +<strong>var catalog = require('./routes/catalog'); //Import routes for "catalog" area of site</strong></pre> + +<p>Next, add the catalog route to the middleware stack below the other routes (add the third line shown below, underneath the other two):</p> + +<pre class="brush: js">app.use('/', index); +app.use('/users', users); +<strong>app.use('/catalog', catalog); // Add catalog routes to middleware chain.</strong></pre> + +<div class="note"> +<p><strong>Note:</strong> We have added our catalog module at a path <code>'/catalog'</code>. This is prepended to all of the paths defined in the catalog module. So for example, to access a list of books, the URL will be: <code>/catalog/books/</code>.</p> +</div> + +<p>That's it. We should now have routes and skeleton functions enabled for all the URLs that we will eventually support on the LocalLibrary website.</p> + +<h3 id="Testing_the_routes">Testing the routes</h3> + +<p>To test the routes, first start the website using your usual approach</p> + +<ul> + <li>The default method + <pre class="brush: bash"><code>// Windows +SET DEBUG=express-locallibrary-tutorial:* & npm start + +// macOS or Linux +DEBUG=express-locallibrary-tutorial:* npm start</code> +</pre> + </li> + <li>If you previously set up <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">nodemon</a>, you can instead use: + <pre><code>// Windows +SET DEBUG=express-locallibrary-tutorial:* & npm <strong>run devstart</strong> + +// macOS or Linux +</code>DEBUG=express-locallibrary-tutorial:* npm <strong style="font-family: inherit; font-size: 1rem;">run devstart</strong> +</pre> + </li> +</ul> + +<p>Then navigate to a number of LocalLibrary URLs, and verify that you don't get an error page (HTTP 404). A small set of URLs are listed below for your convenience:</p> + +<ul> + <li><a href="http://localhost:3000/">http://localhost:3000/</a></li> + <li><a href="http://localhost:3000/catalog">http://localhost:3000/catalog</a></li> + <li><a href="http://localhost:3000/catalog/books">http://localhost:3000/catalog/books</a></li> + <li><a href="http://localhost:3000/catalog/bookinstances/">http://localhost:3000/catalog/bookinstances/</a></li> + <li><a href="http://localhost:3000/catalog/authors/">http://localhost:3000/catalog/authors/</a></li> + <li><a href="http://localhost:3000/catalog/genres/">http://localhost:3000/catalog/genres/</a></li> + <li><a href="http://localhost:3000/catalog/book/5846437593935e2f8c2aa226/">http://localhost:3000/catalog/book/5846437593935e2f8c2aa226</a></li> + <li><a href="http://localhost:3000/catalog/book/create">http://localhost:3000/catalog/book/create</a></li> +</ul> + +<h2 id="Summary">Summary</h2> + +<p>We've now created all the routes for our site, along with dummy controller functions that we can populate with a full implementation in later articles. Along the way we've learned a lot of fundamental information about Express routes, and some approaches for structuring our routes and controllers.</p> + +<p>In our next article we'll create a proper welcome page for the site, using views (templates) and information stored in our models.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="http://expressjs.com/en/starter/basic-routing.html">Basic routing</a> (Express docs)</li> + <li><a href="http://expressjs.com/en/guide/routing.html">Routing guide</a> (Express docs)</li> +</ul> + +<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs")}}</p> + +<p> </p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li> +</ul> + +<p> </p> diff --git a/files/uk/learn/server-side/index.html b/files/uk/learn/server-side/index.html new file mode 100644 index 0000000000..c79d8ea81e --- /dev/null +++ b/files/uk/learn/server-side/index.html @@ -0,0 +1,52 @@ +--- +title: Server-side website programming +slug: Learn/Server-side +tags: + - Beginner + - CodingScripting + - Intro + - Landing + - Learn + - NeedsTranslation + - Server + - Server-side programming + - Topic + - TopicStub +translation_of: Learn/Server-side +--- +<div>{{LearnSidebar}}</div> + +<p class="summary">The <strong><em>Dynamic Websites </em></strong>–<em><strong> Server-side programming</strong></em> topic is a series of modules that show how to create dynamic websites; websites that deliver customised information in response to HTTP requests. The modules provide a generic introduction to server-side programming, along with specific beginner-level guides on how to use the Django (Python) and Express (Node.js/JavaScript) web frameworks to create basic applications.</p> + +<p>Most major websites use some kind of server-side technology to dynamically display different data as required. For example, imagine how many products are available on Amazon, and imagine how many posts have been written on Facebook? Displaying all of these using completely different static pages would be completely inefficient, so instead such sites display static templates (built using <a href="/en-US/docs/Learn/HTML">HTML</a>, <a href="/en-US/docs/Learn/CSS">CSS</a>, and <a href="/en-US/docs/Learn/JavaScript">JavaScript</a>), and then dynamically update the data displayed inside those templates when needed, e.g. when you want to view a different product on Amazon.</p> + +<p>In the modern world of web development, learning about server-side development is highly recommended.</p> + +<h2 id="Learning_pathway">Learning pathway</h2> + +<p>Getting started with server-side programming is usually easier than with client-side development, because dynamic websites tend to perform a lot of very similar operations (retrieving data from a database and displaying it in a page, validating user-entered data and saving it in a database, checking user permissions and logging users in, etc.), and are constructed using web frameworks that make these and other common web server operations easy.</p> + +<p>A basic knowledge of programming concepts (or of a particular programming language) is useful, but not essential. Simlarly, expertise in client-side coding is not required, but a basic knowledge will help you work better with the developers creating your client-side web "front end".</p> + +<p>You will need to understand "how the web works". We recommend that you first read the following topics:</p> + +<ul> + <li><a href="/en-US/docs/Learn/Common_questions/What_is_a_web_server">What is a web server</a></li> + <li><a href="/en-US/docs/Learn/Common_questions/What_software_do_I_need">What software do I need to build a website?</a></li> + <li><a href="/en-US/docs/Learn/Common_questions/Upload_files_to_a_web_server">How do you upload files to a web server?</a></li> +</ul> + +<p>With that basic understanding you'll be ready to work your way through the modules in this section. </p> + +<h2 id="Modules">Modules</h2> + +<p>This topic contains the following modules. You should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks . </p> + +<dl> + <dt><a href="/en-US/docs/Learn/Server-side/First_steps">Server-side website programming first steps</a></dt> + <dd>This module provides server-technology-agnostic information about server-side website programming, including answers to fundamental questions about server-side programming — "what it is", "how it differs from client-side programming", and "why it is so useful" — and an overview of some of the more popular server-side web frameworks and guidance on how to select the most suitable for your site. Lastly we provide an introductory section on web server security.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Django">Django Web Framework (Python)</a></dt> + <dd>Django is an extremely popular and fully featured server-side web framework, written in Python. The module explains why Django is such a good web server framework, how to set up a development environment and how to perform common tasks with it.</dd> + <dt><a href="/en-US/docs/Learn/Server-side/Express_Nodejs">Express Web Framework (Node.js/JavaScript)</a></dt> + <dd>Express is a popular web framwork, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.</dd> +</dl> |