许 志强

许 志强

1660239540

Supabase:使用 Python 的 Postgres 数据库

Supabase 是一个开源的后端即服务 (BaaS),最近在开发人员中越来越受欢迎。Supabase 声称是开源的 Firebase 替代品,并得到了 Yandex、Mozilla 和 Coatue 等大型科技公司的支持。与 Google Firebase 一样,Supabase 还旨在通过提供各种重要的特性和功能(如身份验证、云存储、数据库、分析和边缘功能)来替换现代 Web 和移动应用程序的完整后端。这些服务可以根据网络流量自动扩展,无需任何手动设置。

Google Firebase 的主要问题是供应商锁定,这是公司避免使用这些平台来缩短开发时间的原因之一。就 Supabase 而言,无需担心供应商锁定。Supabase 和 Firebase 之间的另一个显着区别是 Supabase 构建在Postgres 数据库之上,而 Firebase 提供了一个名为 Firestore 的 NoSQL 数据库。如果您有兴趣了解 Google Firebase 提供的 Firestore 数据库,请参阅我之前的文章

在本文中,我们将学习如何在 Supabase 平台上设置 Postgres数据库,并使用 python 编程语言执行基本的 CRUD 操作。我们还将看到一些 SQL 查询来对 Postgres 数据库执行一些 CRUD 操作。

设置 Supabase

导航到Supabase 官方网站并使用您的 GitHub 帐户登录以访问 Supabase。这是一个强制性步骤。

超级基地

使用 Github 帐户登录后,您可以在仪表板上查看所有项目。请注意,免费版本最多允许您创建 2 个项目。让我们继续创建一个新的 Supbase 项目。

超级基地

单击创建新项目按钮后,系统将提示您填写一份表格,其中包含有关您的项目的一些基本信息。继续填写详细信息,完成后,单击创建新项目按钮。请注意,如果您输入的数据库密码较弱,则创建新项目按钮将被禁用。因此,请确保提供强密码。创建项目需要一分钟左右。参考图片如下所示。

超级基地

成功创建项目后,您将被重定向到项目仪表板,如下图所示。由于本文重点介绍 Postgres 数据库,因此我们不会介绍其他可用的服务,例如身份验证或存储。让我们继续在数据库中创建一个 Postgres 表。为此,我们可以单击表格编辑器按钮,它提供了一个简单的 UI 来创建和管理表格。如果您熟悉编写 SQL 查询,则可以选择 SQL 编辑器来创建表并执行其他必需的任务。为简单起见,我将使用表编辑器创建表,但我还将介绍本文另一部分中提供的 SQL 编辑器。

演示

单击创建新表按钮后,系统将提示您输入表名和列名及其数据类型。我将把表命名为“demo-database”并创建一个包含六列的表——id、created_at、name、age、country 和 programming_langauges。id 字段将作为该表的主键。请参考下图以更好地理解。输入所有详细信息后,单击保存按钮以创建表。

演示数据库

现在我们已经创建了一个表,让我们动手把注意力转移到编程部分。

连接到 Supabase 并执行 CRUD 操作

有一个适用于 python 的 Supabase 客户端,可以像使用 pip 的任何其他 python 模块一样安装。让我们继续安装它,然后再继续。

$ pip install supabase

连接到 Supabase 数据库必须做两件事:项目 URL 和 API 密钥。要提取此内容,请导航到设置选项卡并选择 API 部分,您将在其中找到项目 URL 和 API 密钥。复制 URL 和匿名公钥,因为这将用于连接到 Supabase 数据库。

超级基地

现在我们已经拥有了所有凭据,让我们继续连接到 Supabase 数据库。

from supabase import create_client
import json
API_URL = 'your_url'
API_KEY = 'your_key'
supabase = create_client(API_URL, API_KEY)
supabase

现在我们已经成功连接到数据库,让我们了解如何执行基本的 CRUD 操作。

首先让我们看看如何将一条记录插入到数据库中的表中。每条记录都需要是一个包含所有信息的字典。要将记录插入表中,我们使用“insert()”函数,该函数接受记录数据作为字典。

data = {
    'id': 1,
    'name': 'Vishnu',
    'age': 22,
    'country': 'India',
    'programming_languages': json.dumps(['C++', 'python', 'Rust'])
}
supabase.table('demo-database').insert(data).execute() # inserting one recordAPIResponse(data=[{'id': 1, 'created_at': '2022-07-17T08:58:24.105377+00:00', 'name': 'Vishnu', 'age': 22, 'country': 'India', 'programming_languages': '["C++", "python", "Rust"]'}], count=None)

超级基地

现在同样的“insert()”函数也可以用来插入多条记录。为此,我们必须传入一个包含所有记录数据的字典列表。现在让我们看看它的实际效果。

data = [
    {
        'id': 2,
        'name': 'Prakash',
        'age': 37,
        'country': 'India',
        'programming_languages': json.dumps(['C#', 'web assembly'])
    },
    {
        'id': 3,
        'name': 'Arjun',
        'age': 29,
        'country': 'Germany',
        'programming_languages': json.dumps(['python', 'nodejs', 'Rust'])
    },
    {
        'id': 4,
        'name': 'Sanjay',
        'age': 19,
        'country': 'India',
        'programming_languages': json.dumps(['python'])
    },
    {
        'id': 5,
        'name': 'Ram',
        'age': 44,
        'country': 'India',
        'programming_languages': json.dumps(['python', 'Go'])
    }
]
supabase.table('demo-database').insert(data).execute() # inserting multiple recordsAPIResponse(data=[{'id': 2, 'created_at': '2022-07-17T09:02:48.193326+00:00', 'name': 'Prakash', 'age': 37, 'country': 'India', 'programming_languages': '["C#", "web assembly"]'}, {'id': 3, 'created_at': '2022-07-17T09:02:48.193326+00:00', 'name': 'Arjun', 'age': 29, 'country': 'Germany', 'programming_languages': '["python", "nodejs", "Rust"]'}, {'id': 4, 'created_at': '2022-07-17T09:02:48.193326+00:00', 'name': 'Sanjay', 'age': 19, 'country': 'India', 'programming_languages': '["python"]'}, {'id': 5, 'created_at': '2022-07-17T09:02:48.193326+00:00', 'name': 'Ram', 'age': 44, 'country': 'India', 'programming_languages': '["python", "Go"]'}], count=None)

我们可以看到所有记录在我们的仪表板中也是可见的。现在我们已经了解了如何执行插入操作,让我们看看如何从表中获取一些文档。

要从表中获取一些记录,我们可以使用“select()”函数,就像选择 SQL 查询一样。让我们看看这个在行动中有一个更好的理解。

supabase.table('demo-database').select('*').execute().data # fetching documents[{'id': 1,
  'created_at': '2022-07-17T08:58:24.105377+00:00',
  'name': 'Vishnu',
  'age': 22,
  'country': 'India',
  'programming_languages': '["C++", "python", "Rust"]'},
 {'id': 2,
  'created_at': '2022-07-17T09:02:48.193326+00:00',
  'name': 'Prakash',
  'age': 37,
  'country': 'India',
  'programming_languages': '["C#", "web assembly"]'},
 {'id': 3,
  'created_at': '2022-07-17T09:02:48.193326+00:00',
  'name': 'Arjun',
  'age': 29,
  'country': 'Germany',
  'programming_languages': '["python", "nodejs", "Rust"]'},
 {'id': 4,
  'created_at': '2022-07-17T09:02:48.193326+00:00',
  'name': 'Sanjay',
  'age': 19,
  'country': 'India',
  'programming_languages': '["python"]'},
 {'id': 5,
  'created_at': '2022-07-17T09:02:48.193326+00:00',
  'name': 'Ram',
  'age': 44,
  'country': 'India',
  'programming_languages': '["python", "Go"]'}]

“*”表示我们需要从表中返回所有列。这也可以使用我们仪表板中的 SQL 编辑器来完成。让我们继续编写一个简单的 SQL 查询,看看它是如何工作的。

我们可以看到我们在这里也得到了相同的响应。现在,如果我们没有任何类型的过滤,选择查询就非常愚蠢。如果您对 MongoDB 查询稍有了解,则可以轻松理解这部分内容。现在让我们看看几种过滤技术的实际应用。

让我们尝试获取年龄超过 35 岁的所有记录。要执行此操作,我们可以使用过滤技术。在这种情况下,我们将使用“gt()”函数,它代表“大于”运算符。让我们通过在 SQL 编辑器中运行一个普通的 SQL 查询来解决这个问题。

supabase.table('demo-database').select('*').gt('age', 35).execute().data # fetching documents with filtering[{'id': 2,
  'created_at': '2022-07-17T09:02:48.193326+00:00',
  'name': 'Prakash',
  'age': 37,
  'country': 'India',
  'programming_languages': '["C#", "web assembly"]'},
 {'id': 5,
  'created_at': '2022-07-17T09:02:48.193326+00:00',
  'name': 'Ram',
  'age': 44,
  'country': 'India',
  'programming_languages': '["python", "Go"]'}]

我们可以看到 SQL 查询也返回了与响应相同的记录集。现在我们也可以添加多组过滤器。要查看实际情况,让我们尝试获取年龄大于 35 岁但小于 40 岁的所有记录。

supabase.table('demo-database').select('*').gt('age', 35).lt('age', 40).execute().data # multiple filtering[{'id': 2,
  'created_at': '2022-07-17T09:02:48.193326+00:00',
  'name': 'Prakash',
  'age': 37,
  'country': 'India',
  'programming_languages': '["C#", "web assembly"]'}]

现在我们已经了解了如何从表中获取记录,让我们看看如何更新表中的记录。为此,我们使用“update()”函数。让我们尝试将 ID 为 2 的记录更新为 France。我们使用“eq()”函数作为“等于”运算符进行过滤。如果我们不包括这个,表中的所有记录都将被更新。

supabase.table('demo-database').update({"country": "France"}).eq("id", 2).execute() # updating a recordAPIResponse(data=[{'id': 2, 'created_at': '2022-07-17T09:02:48.193326+00:00', 'name': 'Prakash', 'age': 37, 'country': 'France', 'programming_languages': '["C#", "web assembly"]'}], count=None)

 

我们可以看到国家已经成功更新为法国。

现在我们来看最后一个操作,也就是删除操作。要删除一条记录,我们使用“delete()”操作和一些过滤操作,以免表中的所有记录都被删除。这类似于上一节中解释的更新操作。让我们继续从表中删除一条记录。我们将删除 id 为 1 的记录。

supbase.table("demo-database").delete().eq("id", 1).execute() # 删除一条记录APIResponse(data=[{'id': 1, 'created_at': '2022-07 -17T08:58:24.105377+00:00', 'name': 'Vishnu', 'age': 22, 'country': 'India', 'programming_languages': '["C++", "python", "Rust "]'}], 计数=无)

 

我们可以看到对应的记录已经被成功删除了。

结论

几个关键要点:

  • 了解如何在 Supabase 中设置 Postgres 数据库
  • 学习如何使用 python 在 Postgres 数据库上执行基本的 CRUD 操作
  • 学习如何使用 SQL 编辑器编写 SQL 查询

如前所述,Supabase 提供了许多其他服务,如身份验证、云存储、实时数据库和边缘功能。实时数据库功能目前不适用于 python。在接下来的几周内,我将尝试在另一篇文章中介绍 Supabase 提供的云存储服务,敬请期待!

这就是本文的内容。我希望你喜欢阅读这篇文章并学到新的东西。感谢阅读,快乐学习!

来源:https ://www.analyticsvidhya.com/blog/2022/07/introduction-to-supabase-postgres-database-using-python/

  #python #database 

What is GEEK

Buddha Community

Supabase:使用 Python 的 Postgres 数据库
Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development

Art  Lind

Art Lind

1602666000

How to Remove all Duplicate Files on your Drive via Python

Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.

Intro

In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.

Heres a solution

Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.

But How do we do it?

If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?

The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.

There’s a variety of hashing algorithms out there such as

  • md5
  • sha1
  • sha224, sha256, sha384 and sha512

#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc…

You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like init, call, str etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Now there are a number of such special methods, which you might have come across too, in Python. We will just be taking an example of a few of them to understand how they work and how we can use them.

1. init

class AnyClass:
    def __init__():
        print("Init called on its own")
obj = AnyClass()

The first example is _init, _and as the name suggests, it is used for initializing objects. Init method is called on its own, ie. whenever an object is created for the class, the init method is called on its own.

The output of the above code will be given below. Note how we did not call the init method and it got invoked as we created an object for class AnyClass.

Init called on its own

2. add

Let’s move to some other example, add gives us the ability to access the built in syntax feature of the character +. Let’s see how,

class AnyClass:
    def __init__(self, var):
        self.some_var = var
    def __add__(self, other_obj):
        print("Calling the add method")
        return self.some_var + other_obj.some_var
obj1 = AnyClass(5)
obj2 = AnyClass(6)
obj1 + obj2

#python3 #python #python-programming #python-web-development #python-tutorials #python-top-story #python-tips #learn-python

Arvel  Parker

Arvel Parker

1593156510

Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type