mirror of
https://github.com/LCTT/TranslateProject.git
synced 2024-12-26 21:30:55 +08:00
Merge remote-tracking branch 'LCTT/master'
This commit is contained in:
commit
09c6c00dbd
@ -1,20 +1,22 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: (MjSeven)
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: reviewer: (wxy)
|
||||
[#]: publisher: (wxy)
|
||||
[#]: url: (https://linux.cn/article-12900-1.html)
|
||||
[#]: subject: (How to use Serializers in the Django Python web framework)
|
||||
[#]: via: (https://opensource.com/article/20/11/django-rest-framework-serializers)
|
||||
[#]: author: (Renato Oliveira https://opensource.com/users/renato-oliveira)
|
||||
|
||||
如何在 Python Web 框架 Django 中使用序列化器
|
||||
======
|
||||
序列化将数据转换为方便存储或传输的格式,然后将其重构以供使用。DRF 具有最知名的序列化器。
|
||||
![Net catching 1s and 0s or data in the clouds][1]
|
||||
|
||||
序列化是将数据转换为可以存储或传输的格式,然后对其进行重构的过程。在开发应用程序或将数据存储在数据库、内存或将其转换为文件时,一直会用到它。
|
||||
> 序列化用于将数据转换为方便存储或传输的格式,然后将其重新构建以供使用。DRF 是最具有知名的序列化器。
|
||||
|
||||
我最近帮助 [Labcodes][2] 的两名初级开发人员理解序列化器,同时我认为与 Opensource.com 的读者分享我的方法会更好。
|
||||
![](https://img.linux.net.cn/data/attachment/album/202012/08/220845q5tz7cfftze5oem5.jpg)
|
||||
|
||||
序列化是将数据转换为可以存储或传输的格式,然后对其进行重新构建的过程。在开发应用程序或将数据存储在数据库、内存或将其转换为文件时,一直会用到它。
|
||||
|
||||
我最近帮助 [Labcodes][2] 的两名初级开发人员理解序列化器,我想也可以与诸位读者分享一下我的方法。
|
||||
|
||||
假设你正在编写一个电子商务网站,你有一个订单,该订单记录了某人在某个日期以某种价格购买了一个产品:
|
||||
|
||||
@ -39,7 +41,7 @@ def serialize_order(order):
|
||||
}
|
||||
```
|
||||
|
||||
如果你想从数据库中获取一些数据,你可以获取字典数据并将其转换为订单对象:
|
||||
如果你想从数据库中获取一些数据,你可以获取字典数据并将其转换为订单对象(`Order`):
|
||||
|
||||
```
|
||||
def deserialize_order(order_data):
|
||||
@ -53,7 +55,7 @@ def deserialize_order(order_data):
|
||||
|
||||
这对于简单的数据非常直接了当,但是当你需要处理一些由复杂属性构成的复杂对象时,这种方法就无法很好地扩展。你还需要处理不同类型字段的验证,这需要手工完成大量工作。
|
||||
|
||||
此时序列化框架可以很方便的派上用场。它们使你可以创建带有少量模板的序列化器,这将适用于复杂的情况。
|
||||
此时框架的序列化可以很方便的派上用场。它们使你可以创建带有少量模板的序列化器,这将适用于复杂的情况。
|
||||
|
||||
[Django][3] 提供了一个序列化模块,允许你将模型“转换”为其它格式:
|
||||
|
||||
@ -63,7 +65,7 @@ from django.core import serializers
|
||||
serializers.serialize('json', Order.objects.all())
|
||||
```
|
||||
|
||||
它涵盖了 Web 应用程序最常用的种类,例如 JSON、YAML 和 XML。但是你也可以使用第三方序列化器或创建自己的序列化器。你只需要在 settings.py 文件中注册它:
|
||||
它涵盖了 Web 应用程序最常用的种类,例如 JSON、YAML 和 XML。但是你也可以使用第三方序列化器或创建自己的序列化器。你只需要在 `settings.py` 文件中注册它:
|
||||
|
||||
```
|
||||
# settings.py
|
||||
@ -72,7 +74,7 @@ SERIALIZATION_MODULES = {
|
||||
}
|
||||
```
|
||||
|
||||
要创建自己的 `MyFormatSerializer`,你需要实现 `.serialize()` 方法并接受一个 queryset 和其它选项作为参数:
|
||||
要创建自己的 `MyFormatSerializer`,你需要实现 `.serialize()` 方法并接受一个查询集和其它选项作为参数:
|
||||
|
||||
```
|
||||
class MyFormatSerializer:
|
||||
@ -88,7 +90,7 @@ from django.core import serializers
|
||||
serializers.serialize('my_format', Order.objects.all())
|
||||
```
|
||||
|
||||
你可以使用 options 参数来定义序列化程序的行为。例如,如果要定义在处理 `ForeignKeys` 时要使用嵌套序列化,或者只希望数据返回其主键,你可以传递一个 `flat=True` 参数作为选项,并在方法中处理:
|
||||
你可以使用选项参数来定义序列化程序的行为。例如,如果要定义在处理 `ForeignKeys` 时要使用嵌套序列化,或者只希望数据返回其主键,你可以传递一个 `flat=True` 参数作为选项,并在方法中处理:
|
||||
|
||||
```
|
||||
class MyFormatSerializer:
|
||||
@ -100,9 +102,9 @@ class MyFormatSerializer:
|
||||
|
||||
使用 Django 序列化的一种方法是使用 `loaddata` 和 `dumpdata` 管理命令。
|
||||
|
||||
### DRF 序列化
|
||||
### DRF 序列化器
|
||||
|
||||
在 Django 社区中,[Django REST framework][4](DRF) 提供了最著名的序列化器。尽管你可以使用 Django 的序列化器来构建将在 API 中响应的 JSON,但 REST 框架中的序列化器提供了更出色的功能,可以帮助你处理并轻松验证复杂的数据。
|
||||
在 Django 社区中,[Django REST 框架][4](DRF)提供了最著名的序列化器。尽管你可以使用 Django 的序列化器来构建将在 API 中响应的 JSON,但 REST 框架中的序列化器提供了更出色的功能,可以帮助你处理并轻松验证复杂的数据。
|
||||
|
||||
在订单的例子中,你可以像这样创建一个序列化器:
|
||||
|
||||
@ -126,7 +128,7 @@ serializer.data
|
||||
# {'product': 'pen', 'customer': 'renato', 'price': '10.50', 'date': '2020-08-16'}
|
||||
```
|
||||
|
||||
为了能够从数据返回实例,你需要实现两个方法:create 和 update:
|
||||
为了能够从数据返回实例,你需要实现两个方法:`create` 和 `update`:
|
||||
|
||||
```
|
||||
from rest_framework import serializers
|
||||
@ -155,9 +157,9 @@ serializer.is_valid()
|
||||
serializer.save()
|
||||
```
|
||||
|
||||
### Model 序列化
|
||||
### 模型序列化器
|
||||
|
||||
序列化数据时,通常需要从数据库进行数据处理,即你创建的模型。ModelSerializer 与 ModelForm 一样,提供了一个 API,用于从模型创建序列化器。假设你有一个订单模型:
|
||||
序列化数据时,通常需要从数据库(即你创建的模型)进行数据处理。`ModelSerializer` 与 `ModelForm` 一样,提供了一个 API,用于从模型创建序列化器。假设你有一个订单模型:
|
||||
|
||||
```
|
||||
from django.db import models
|
||||
@ -182,9 +184,9 @@ class OrderSerializer(serializers.ModelSerializer):
|
||||
|
||||
Django 会自动在序列化器中包含所有模型字段,并创建 `create` 和 `udpate` 方法。
|
||||
|
||||
### 在基于类的视图中使用序列化器 (CBVs)
|
||||
### 在基于类的视图(CBV)中使用序列化器
|
||||
|
||||
像 Django CBV 中的表单一样,序列化器可以很好地与 DRF 集成。你可以设置 `serializer_class` 属性,方便序列化器用于视图:
|
||||
像 Django CBV 中的 `Forms` 一样,序列化器可以很好地与 DRF 集成。你可以设置 `serializer_class` 属性,方便序列化器用于视图:
|
||||
|
||||
```
|
||||
from rest_framework import generics
|
||||
@ -208,11 +210,11 @@ class OrderListCreateAPIView(generics.ListCreateAPIView):
|
||||
return OrderSerializer
|
||||
```
|
||||
|
||||
在 CBV 中还有其它与序列化器交互的方法。例如,[get_serializer()][5] 返回一个已经实例化的序列化器,[get_serializer_context()][6] 返回创建实例时传递给序列化器的参数。对于创建或更新数据的视图,有 `create` 和 `update`,它们使用 `is_valid` 方法验证数据,还有 [perform_create][7] 和 [perform_update][8] 调用序列化的 `save` 方法。
|
||||
在 CBV 中还有其它与序列化器交互的方法。例如,[get_serializer()][5] 返回一个已经实例化的序列化器,[get_serializer_context()][6] 返回创建实例时传递给序列化器的参数。对于创建或更新数据的视图,有 `create` 和 `update`,它们使用 `is_valid` 方法验证数据,还有 [perform_create][7] 和 [perform_update][8] 调用序列化器的 `save` 方法。
|
||||
|
||||
### 了解更多
|
||||
|
||||
要了解更多资源,参考我朋友 André Ericson 的[经典 Django REST Framework][9] 网站。它是一个[基于类的经典视图][10]的 REST Framework 版本,可让你深入查看组成 DRF 的类。当然,官方[文档][11]也是一个很棒的资源。
|
||||
要了解更多资源,参考我朋友 André Ericson 的[经典 Django REST 框架][9]网站。它是一个[基于类的经典视图][10]的 REST 框架版本,可让你深入查看组成 DRF 的类。当然,官方[文档][11]也是一个很棒的资源。
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
@ -221,7 +223,7 @@ via: https://opensource.com/article/20/11/django-rest-framework-serializers
|
||||
作者:[Renato Oliveira][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[MjSeven](https://github.com/MjSeven)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
校对:[wxy](https://github.com/wxy)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
@ -0,0 +1,81 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: ( )
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: subject: (3 ways Kubernetes optimizes your IT budget)
|
||||
[#]: via: (https://opensource.com/article/20/12/it-budget-kubernetes)
|
||||
[#]: author: (John Allen https://opensource.com/users/johnallen)
|
||||
|
||||
3 ways Kubernetes optimizes your IT budget
|
||||
======
|
||||
Automation is not only good for IT, it's also beneficial to your
|
||||
company's bottom line.
|
||||
![A dollar sign in a network][1]
|
||||
|
||||
Businesses all over the world are facing extraordinary challenges, and adapting to new ways of work is essential to their survival and progress. The importance of IT workers and systems can't be overstated; with companies looking for innovative ways to adjust, often with reduced resources, automation is increasingly central to day-to-day operations.
|
||||
|
||||
Many of these companies have turned to [Kubernetes][2] to ensure their products and services provide the best possible experience to users. Kubernetes is a container orchestration tool developed by Google. It's been open source since 2014, and over the past few years, a lot of tech success stories (including Netflix and hugely popular online games) have been built on using its tools to coordinate applications.
|
||||
|
||||
![Kubernetes microservices architecture][3]
|
||||
|
||||
Kubernetes' microservice architecture enhances performance by breaking complex apps into components. (John Allen, [CC BY-SA 4.0][4])
|
||||
|
||||
The Kubernetes system's essential role is to make hosting an application with containers manageable. Traditional monolith systems put an app's entire code in one place. In contrast, containers split that code into smaller microservices that perform specific tasks (e.g., controlling volume or processing a payment).
|
||||
|
||||
That might sound like a huge increase in workload, with thousands of containers needing separate maintenance. But Kubernetes enables a regular team of engineers to manage an enormous number of containers.
|
||||
|
||||
If you want to understand the system in detail, [_A beginner's guide to Kubernetes container orchestration_][5] details the what, how, and why of Kubernetes, and it is well worth checking out. From a purely budgeting perspective, though, there are some major benefits to Kubernetes that could maximize your IT resources.
|
||||
|
||||
### Automation
|
||||
|
||||
One of Kubernetes' key benefits is [automation][6], and this is closely linked to the system's utility as an orchestration tool. It can automate individual tasks, thereby streamlining your IT resources by reducing the need for human intervention, but orchestration is required to coordinate those tasks into an overall process.
|
||||
|
||||
Even if each task is perfectly automated, the overall process won't be effective unless those tasks are performed correctly _together_. Essentially, Kubernetes is the conductor that ensures the whole process works.
|
||||
|
||||
Since applications are based on consistently performing the same tasks as part of an overall process, automating each task—as well as the orchestration of those tasks—builds reliability into your infrastructure. This infrastructure is the basis of a good user experience and, therefore, of a strong product.
|
||||
|
||||
By automating much of the day-to-day running of your application, you can focus your IT budget on areas that maximize your return on investment and fund innovations to grow your business.
|
||||
|
||||
### Performance
|
||||
|
||||
Whether your product is a hugely popular online video game or part of the new wave of omnichannel contact center solutions, you need a guaranteed level of performance. The Kubernetes architecture is the key to its popularity, with several important features built in to ensure the performance of even the most complex processes.
|
||||
|
||||
![Kubernetes interface][7]
|
||||
|
||||
Kubernetes' interface makes monitoring performance easier. (John Allen, [CC BY-SA 4.0][4])
|
||||
|
||||
For example, good call-center software needs to run a huge number of processes to maximize customers' potential to reach their desired outcome. Guaranteeing the performance of each one of these elements is essential. Distributing the software's tasks among containers isolates each task. This means there is less that can go wrong, which simplifies the process of fixing errors or updating software. Compartmentalizing tasks, rather than running a monolith, puts less strain on your servers, thereby improving your hardware's efficiency.
|
||||
|
||||
In addition to reducing your IT budget by decreasing time spent on maintenance, this leads to a better user experience. This, in turn, has the potential to produce greater uptake and increased profitability.
|
||||
|
||||
### Maintenance
|
||||
|
||||
If your business relies on users' ability to interact with your application, you will understand the dread of being down for maintenance. Kubernetes can help eliminate many of the issues that lead to reduced availability. Monolith architecture maintenance requires an entire system to be taken down, fixed, tested, and re-deployed, which costs time and money and frustrates users. A microservices architecture allows issues to be isolated and resolved without downtime, meaning your app is always ready for use.
|
||||
|
||||
The mutability of Kubernetes means it can adapt to a variety of infrastructures across physical, virtual, cloud, and hybrid environments. The maintenance involved with building for Kubernetes (or transferring from monolith to container) adapts to the experience of developers looking to find the most effective solution.
|
||||
|
||||
With more and more people working from home, enabling workers to coordinate remotely on complex projects is essential. Videoconferencing and providing virtual phone numbers are highly effective ways of ensuring smooth project management. Knowing you're working within a system that can deal with a huge number of problems and provide practical solutions is also invaluable. Because Kubernetes is open source, it also benefits from shared knowledge that lets you implement performance-enhancing features as they are developed.
|
||||
|
||||
Naturally, implementing new infrastructure will incur upfront costs. However, the long-term benefits mean it's worth considering Kubernetes. Not only can your company optimize its existing budget and services, but you can also explore innovative new ways of growing. Switching to Kubernetes sooner rather than later may lead to improved performance, automated IT processes, lower maintenance, and happier users.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/20/12/it-budget-kubernetes
|
||||
|
||||
作者:[John Allen][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/johnallen
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/osdc_whitehurst_money.png?itok=ls-SOzM0 (A dollar sign in a network)
|
||||
[2]: https://kubernetes.io/
|
||||
[3]: https://opensource.com/sites/default/files/uploads/kubernetesarchitecture.jpg (Kubernetes microservices architecture)
|
||||
[4]: https://creativecommons.org/licenses/by-sa/4.0/
|
||||
[5]: https://opensource.com/article/20/6/container-orchestration
|
||||
[6]: https://opensource.com/article/20/11/orchestration-vs-automation
|
||||
[7]: https://opensource.com/sites/default/files/uploads/kubernetesui.jpg (Kubernetes interface)
|
@ -0,0 +1,92 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: ( )
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: subject: (Collaborate on text with Etherpad, an open source alternative to Google Docs)
|
||||
[#]: via: (https://opensource.com/article/20/12/etherpad)
|
||||
[#]: author: (Seth Kenlon https://opensource.com/users/seth)
|
||||
|
||||
Collaborate on text with Etherpad, an open source alternative to Google Docs
|
||||
======
|
||||
Etherpad is a great text editor for working collaboratively in the cloud
|
||||
or using someone else's machine.
|
||||
![a checklist for a team][1]
|
||||
|
||||
Sometimes you just have to edit text on the cloud. Maybe you're using a computer you don't own to work on a document you want to keep. Maybe you need to collaborate with other people on a shared document. Or maybe your primary computing interface is a web browser, and you have no interest in using local applications or local storage.
|
||||
|
||||
For many reasons, it's pretty common these days to use the network as your computer, and it's always important to have open source tools for your work. For several years now, I've been a happy Nextcloud user—and a serious user of its default text editor, but it is not a public platform by design. So for collaboration with friends and colleagues, I use [Etherpad][2].
|
||||
|
||||
### Install Etherpad
|
||||
|
||||
Etherpad is open source, which is often a difficult concept to understand when talking about online tools. Whether a web app is or is not open source rarely seems to matter much because you're using an app installed on somebody else's server (or [cluster][3], in many cases). You don't actually own any cloud service, and if the service disappears, then quite probably the data you stored there will also disappear. However, you _can_ take ownership of open source services because you can install them on your own server or cluster. And with Etherpad, you can export your work even when you're using someone else's installation.
|
||||
|
||||
If you run your own server or cloud, you can [download][4] the latest version from Etherpad's website. It's written in Node.js and has options for running in a container, so installing it on a Linux server is easy.
|
||||
|
||||
### Access Etherpad without installing
|
||||
|
||||
You can also use Etherpad on somebody else's server. There are several instances of Etherpad on the internet that are open for public use, including [pad.riseup.net][5]. You might also consider banding together with other open source enthusiasts to host some shared services. This has been my solution lately, and I've found it to be a good compromise between running my own services and trusting someone else to run everything for me.
|
||||
|
||||
### Start a new document
|
||||
|
||||
To start using Etherpad, navigate to a public Etherpad instance and follow its instructions. Usually, the instructions are to type a unique name for your document and get to work, but some instances may require you to sign up for a login account.
|
||||
|
||||
Once you get used to Etherpad, you'll find that starting a new document is also dynamic: You can just type your Etherpad document path's URL followed by what you want to name your document, and a new file will be created for you. For instance, if you're using an Etherpad instance installed at `pad.example.com`, and you know that all documents are stored at `pad.example.com/p`, then you can start a new document called `note-to-self` by navigating to `pad.example.com/p/note-to-self`. Some instances have time limits on how long a document persists, while others let you set a document's life.
|
||||
|
||||
If you're using a public instance, then your document is accessible to anyone. It's not readily discoverable, so you probably need to share the URL with others, but without a login, you're relying on obscurity for document security. For most collaborative tasks, this is acceptable to me, but if it's a concern to you, be sure to use an Etherpad instance that requires authorization.
|
||||
|
||||
### Etherpad editing features
|
||||
|
||||
Etherpad is light on features. Its primary benefit is that it's a real-time collaborative editor. Whether you're writing code, a business document, school papers, personal notes, or something else, it treats everything the same: as plain text. It has no syntax highlighting nor interpretive styling or rendering aside from bold, italic, underline, and strikethrough.
|
||||
|
||||
It does have revision control, with an easy-to-use "playback" feature that lets you step through creating a document as easily as you scan through a video or audio file.
|
||||
|
||||
![Etherpad playback function][6]
|
||||
|
||||
(Seth Kenlon, [CC BY-SA 4.0][7])
|
||||
|
||||
### Collaborative editing
|
||||
|
||||
Etherpad is a collaborative editor, so you can work on the same document at the same time someone else is working on it. You see each other's changes, color-coded to identify who is doing what by default. You can change your color identifier by clicking your profile in the upper-right corner of the Etherpad interface. If you don't like seeing a document marked up with different colors, you can deactivate the feature entirely.
|
||||
|
||||
There's also a chat function in the Etherpad window, so you can discuss your work in a chat window rather than typing chat questions into your working document (a common hack on similar platforms).
|
||||
|
||||
![Etherpad][8]
|
||||
|
||||
(Seth Kenlon, [CC BY-SA 4.0][7])
|
||||
|
||||
### Import and export
|
||||
|
||||
By default, Etherpad can import and export plaintext and HTML. This is useful for many reasons, not the least of which is your own data security. Because Etherpad exists on a cloud, and it's often not _your_ cloud, you need to make sure you've got backups of your important data.
|
||||
|
||||
If the Etherpad administrator has installed some extra backend applications that Etherpad can use for diverse format support, you may also be able to import and export ODT (a common LibreOffice format) and other popular document types.
|
||||
|
||||
### Write on the cloud
|
||||
|
||||
Etherpad is an excellent tool. I use it for collaboration at work, as an easy way to develop ideas while away from my own computer, and of course, to author things like this article. When I use it, I usually forget that it's an editor in my browser because it doesn't "feel" like a browser editor to me. After I switch to another tab in my browser, I often find myself absent-mindedly pressing **Alt**+**Tab** to get back to Etherpad, thinking I've been writing in a desktop app as usual. I take that as a good sign.
|
||||
|
||||
If you need a reliable and pleasant editor that lives on the network, give Etherpad a try.
|
||||
|
||||
Take a look at five great open source alternatives to Google Docs.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/20/12/etherpad
|
||||
|
||||
作者:[Seth Kenlon][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/seth
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/checklist_hands_team_collaboration.png?itok=u82QepPk (a checklist for a team)
|
||||
[2]: http://etherpad.org
|
||||
[3]: https://opensource.com/article/20/6/kubernetes-raspberry-pi
|
||||
[4]: https://etherpad.org/#download
|
||||
[5]: https://pad.riseup.net/
|
||||
[6]: https://opensource.com/sites/default/files/uploads/etherpad-revision.jpg (Etherpad playback function)
|
||||
[7]: https://creativecommons.org/licenses/by-sa/4.0/
|
||||
[8]: https://opensource.com/sites/default/files/uploads/etherpad_0.jpg (Etherpad)
|
@ -0,0 +1,126 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: ( )
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: subject: (Learn Bash by writing an interactive game)
|
||||
[#]: via: (https://opensource.com/article/20/12/learn-bash)
|
||||
[#]: author: (Jim Hall https://opensource.com/users/jim-hall)
|
||||
|
||||
Learn Bash by writing an interactive game
|
||||
======
|
||||
Programming a simple game is a great way to practice a new language and
|
||||
compare it against others you know.
|
||||
![bash logo on green background][1]
|
||||
|
||||
Learning a new programming language can be fun. Whenever I try to learn a new one, I focus on defining variables, writing a statement, and evaluating expressions. Once I have a general understanding of those concepts, I can usually figure out the rest on my own. Most programming languages have some similarities, so once you know one programming language, learning the next one is a matter of figuring out the unique details and recognizing the differences in it.
|
||||
|
||||
To help me practice a new programming language, I like to write a few test programs. One sample program I often write is a simple "guess the number" program, where the computer picks a number between one and 100 and asks me to guess the number. The program loops until I guess correctly.
|
||||
|
||||
The "guess the number" program exercises several concepts in programming languages: how to assign values to variables, how to write statements, and how to perform conditional evaluation and loops. It's a great practical experiment for learning a new programming language.
|
||||
|
||||
### Guess the number in Bash
|
||||
|
||||
[Bash][2] is the standard shell for most Linux systems. Aside from providing a rich command-line user interface, Bash also supports a complete programming language in the form of _scripts_.
|
||||
|
||||
If you're not familiar with Bash, I recommend these introductions:
|
||||
|
||||
* [What is Bash?][3]
|
||||
* [Get started with Bash programming][4]
|
||||
* [Get started with Bash scripting for sysadmins][5]
|
||||
* [How to write functions in Bash][6]
|
||||
* [Read more about Bash][7]
|
||||
|
||||
|
||||
|
||||
You can explore Bash by writing a version of the "guess the number" game. Here is my implementation:
|
||||
|
||||
|
||||
```
|
||||
#!/bin/bash
|
||||
|
||||
number=$(( $RANDOM % 100 + 1 ))
|
||||
|
||||
echo "Guess a number between 1 and 100"
|
||||
|
||||
guess=0
|
||||
|
||||
while [ "0$guess" -ne $number ] ; do
|
||||
read guess
|
||||
[ "0$guess" -lt $number ] && echo "Too low"
|
||||
[ "0$guess" -gt $number ] && echo "Too high"
|
||||
done
|
||||
|
||||
echo "That's right!"
|
||||
exit 0
|
||||
```
|
||||
|
||||
### Breaking down the script
|
||||
|
||||
The first line in the script, `#!/bin/bash` tells Linux to run this script using the Bash shell. Every script starts with the `#!` character pair, which indicates this is a shell script. What immediately follows `#!` is the shell to run. In this case, `/bin/bash` is the Bash shell.
|
||||
|
||||
To assign a value to a variable, list the variable's name followed by the `=` sign. For example, the statement `guess=0` assigns a zero value to the `guess` variable.
|
||||
|
||||
You can also prompt the user to enter a value using the `read` statement. If you write `read guess`, Bash waits for the user to enter some text then stores that value in the `guess` variable.
|
||||
|
||||
To reference the value of a variable, use `$` before the variable name. So, having stored a value in the `guess` variable, you can retrieve it using `$guess`.
|
||||
|
||||
You can use whatever names you like for variables, but Bash reserves a few special variable names for itself. One special variable is `RANDOM`, which generates a very large random number every time you reference it.
|
||||
|
||||
If you want to perform an operation at the same time you store a value, you need to enclose the statement in special brackets. This tells Bash to execute that statement first, and the `=` stores the resulting value in the variable. To evaluate a mathematical expression, use `$(( ))` around your statement. The double parentheses indicate an _arithmetic expression_. In my example, `number=$(( $RANDOM % 100 + 1 ))` evaluates the expression `$RANDOM % 100 + 1` and then stores the value in the `number` variable.
|
||||
|
||||
Standard arithmetic operators such as `+` (plus), `-` (minus), `*` (multiply), `/` (divide), and `%` (modulo) apply.
|
||||
|
||||
That means the statement `number=$(( $RANDOM % 100 + 1 ))` generates a random number between one and 100. The modulo operator (`%`) returns the _remainder_ after dividing two numbers. In this case, Bash divides a random number by 100, leaving a remainder in the range zero to 99. By adding one to that value, you get a random number between one and 100.
|
||||
|
||||
Bash supports _conditional expressions_ and _flow control_ like loops. In the "guess the number" game, Bash continues looping as long as the value in `guess` is not equal to `number`. If the guess is less than the random number, Bash prints "Too low," and if the guess is greater than the number, Bash prints "Too high."
|
||||
|
||||
### How it works
|
||||
|
||||
Now that you've written your Bash script, you can run it to play the "guess the number" game. Continue guessing until you find the correct number:
|
||||
|
||||
|
||||
```
|
||||
Guess a number between 1 and 100
|
||||
50
|
||||
Too high
|
||||
30
|
||||
Too high
|
||||
20
|
||||
Too high
|
||||
10
|
||||
Too low
|
||||
15
|
||||
Too high
|
||||
13
|
||||
Too low
|
||||
14
|
||||
That's right!
|
||||
```
|
||||
|
||||
Every time you run the script, Bash will pick a different random number.
|
||||
|
||||
This "guess the number" game is a great introductory program when learning a new programming language because it exercises several common programming concepts in a pretty straightforward way. By implementing this simple game in different programming languages, you can demonstrate some core concepts and compare details in each language.
|
||||
|
||||
Do you have a favorite programming language? How would you write the "guess the number" game in it? Follow this article series to see examples of other programming languages that might interest you.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/20/12/learn-bash
|
||||
|
||||
作者:[Jim Hall][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/jim-hall
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/bash_command_line.png?itok=k4z94W2U (bash logo on green background)
|
||||
[2]: https://en.wikipedia.org/wiki/Bash_(Unix_shell)
|
||||
[3]: https://opensource.com/resources/what-bash
|
||||
[4]: https://opensource.com/article/20/4/bash-programming-guide
|
||||
[5]: https://opensource.com/article/20/4/bash-sysadmins-ebook
|
||||
[6]: https://opensource.com/article/20/6/bash-functions
|
||||
[7]: https://opensource.com/tags/bash
|
@ -0,0 +1,114 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: ( )
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: subject: (How to Pretty Print JSON File in Linux Terminal)
|
||||
[#]: via: (https://itsfoss.com/pretty-print-json-linux/)
|
||||
[#]: author: (Abhishek Prakash https://itsfoss.com/author/abhishek/)
|
||||
|
||||
How to Pretty Print JSON File in Linux Terminal
|
||||
======
|
||||
|
||||
[JSON][1] files are awesome because they store collection of data in a human-readable format. However, reading the JSON file can be a pain if the JSON file is minified.
|
||||
|
||||
Take this for an example:
|
||||
|
||||
![Minified JSON is difficult to read][2]
|
||||
|
||||
A computer can easily read it. Even a human can still read it but if JSON file is properly formatted to display the content, it will be much easier. I mean JSON files are supposed to read like this after all:
|
||||
|
||||
![Pretty Printed JSON is easier to read][3]
|
||||
|
||||
You can use most text editor with some plugins to display it with proper formatting. However, if you are stuck to a terminal or if you want to do it in your shell script, things will be different.
|
||||
|
||||
If you got a minified file, let me show you how to pretty print the JSON file in Linux terminal.
|
||||
|
||||
### Pretty print JSON with jq command in Linux
|
||||
|
||||
[jq][4] is a command line JSON processor. You can use it to slice, filter, map and transform structured data. I am not going in details about using jq command line tool here.
|
||||
|
||||
To use jq, you need to install it first. You can use your [distribution’s package manager][5] to install it. With [universe repository enabled][6], you can install it on Ubuntu using the apt command:
|
||||
|
||||
```
|
||||
sudo apt install jq
|
||||
```
|
||||
|
||||
Once you have it installed, use it in the following manner to pretty print JSON file on the display:
|
||||
|
||||
```
|
||||
jq . sample.json
|
||||
```
|
||||
|
||||
![Pretty printed JSON file][7]
|
||||
|
||||
You may also tempt to use cat but I believe it one of the useless use of cat command.
|
||||
|
||||
```
|
||||
cat sample.json | jq
|
||||
```
|
||||
|
||||
Keep in mind that the above command will not impact the original JSON file. No changes will be written to it.
|
||||
|
||||
You probably already know [how to redirect the command output to a file in Linux][8]. You probably also know that you cannot redirect to the same file and the tee command is not guaranteed to work all the time.
|
||||
|
||||
If you want to modify the original JSON file with pretty print format, you can pipe the parsed output to a new file and then copy it to the original JSON file.
|
||||
|
||||
```
|
||||
jq . sample.json > pretty.json
|
||||
```
|
||||
|
||||
![Pretty printing JSON file in Linux Terminal][9]
|
||||
|
||||
#### Bonus: Minify a JSON file with jq command
|
||||
|
||||
Let’s take a reverse stance and minify a well formatted JSON file. To minify a JSON file, you can use the compact option -c.
|
||||
|
||||
```
|
||||
jq -c < pretty.json
|
||||
```
|
||||
|
||||
![Minified JSON file display][10]
|
||||
|
||||
You can also use cat and redirection if you want:
|
||||
|
||||
```
|
||||
cat pretty.json | jq -c
|
||||
```
|
||||
|
||||
### Using Python to pretty print JSON file in Linux
|
||||
|
||||
It’s more likely that you have Python installed on your system. If that’s the case, you can use it pretty print the JSON file in the terminal:
|
||||
|
||||
```
|
||||
python3 -m json.tool sample.json
|
||||
```
|
||||
|
||||
![Pretty printing JSON with Python][11]
|
||||
|
||||
I know there are other ways to parse JSON file and print it with proper format. You may explore them on your own but these two are sufficient to do the job which is to pretty print JSON file.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://itsfoss.com/pretty-print-json-linux/
|
||||
|
||||
作者:[Abhishek Prakash][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://itsfoss.com/author/abhishek/
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://www.json.org
|
||||
[2]: https://i1.wp.com/itsfoss.com/wp-content/uploads/2020/12/print-json.png?resize=759%2C253&ssl=1
|
||||
[3]: https://i1.wp.com/itsfoss.com/wp-content/uploads/2020/12/pretty-printed-json.png?resize=696%2C538&ssl=1
|
||||
[4]: https://stedolan.github.io/jq/
|
||||
[5]: https://itsfoss.com/package-manager/
|
||||
[6]: https://itsfoss.com/ubuntu-repositories/
|
||||
[7]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2020/12/pretty-print-json-linux-terminal.png?resize=750%2C557&ssl=1
|
||||
[8]: https://itsfoss.com/save-command-output-to-file-linux/
|
||||
[9]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2020/12/pretty-printing-json-linux-terminal.png?resize=750%2C576&ssl=1
|
||||
[10]: https://i2.wp.com/itsfoss.com/wp-content/uploads/2020/12/minify-json-file-linux.png?resize=777%2C253&ssl=1
|
||||
[11]: https://i2.wp.com/itsfoss.com/wp-content/uploads/2020/12/pretty-print-json-with-python.png?resize=777%2C557&ssl=1
|
Loading…
Reference in New Issue
Block a user