Skip to content

2023

Saga Pattern in Microservices Architecture

"The whole is greater than the sum of its parts," a sentiment articulated by Plato, perfectly encapsulates the essence of great architecture. Great architecture is a blend of experience (patterns, anti-patterns, and battle scars), creativity (thinking outside the box, prototyping, and utilizing the scientific method), and mechanical sympathy (understanding a machine's operations at a lower level). Achieving the best architecture is deceptively simple in concept but remarkably difficult in practice.

Introduction

In the realm of microservices architecture, maintaining data consistency and integrity across multiple services is challenging. As systems become increasingly distributed and complex, traditional transactional methods often fall short. This is where the Saga pattern comes to our aid. In this blog post, we will delve into the Saga pattern, discussing its importance in microservices architecture, its benefits, considerations for implementation, and real-world applications.

What is the Saga Pattern?

The Saga pattern is a design approach that facilitates the management of long-lived transactions across multiple microservices. It tackles the issue of consistency in distributed systems by segmenting a large transaction into a series of smaller, local transactions. Each local transaction represents a step in a broader business process, and the sequence of these local transactions constitutes a saga.

The core concept of the Saga pattern is that compensating actions can reverse the effects of completed transactions in the event of failures or errors. This enables the system to maintain data integrity and eventually attain a consistent state.

In the context of microservices, virtually everything can be considered a saga, especially any process involving more than one microservice. A step in a saga generally performs one of the following tasks:

  • Interacting with a database
  • Invoking another microservice
  • Publishing an event

Benefits of the Saga Pattern

  1. Improved Data Consistency: By decomposing transactions into smaller steps and incorporating compensating actions, the Saga pattern ensures that data remains consistent across multiple services, even when failures occur.

  2. Scalability and Availability: Because microservices can be scaled and deployed independently, each service participating in a saga can manage its workload efficiently. This contributes to the system's overall scalability and availability.

  3. Flexibility and Loose Coupling: The Saga pattern encourages loose coupling between services, as each service is accountable for its segment of the complete saga. This enables independent development, deployment, and maintenance of services, allowing teams to operate autonomously.

Implementing the Saga Pattern

To put the Saga pattern into practice, one can adopt various approaches. Here are two common ones:

  1. Choreography-based Saga: In this model, each service in the saga directly communicates with the other services. They publish events or messages to indicate the completion of their local transactions, and other services subscribe to these events and react accordingly. While the choreography approach eliminates the need for a centralized orchestrator, it requires meticulous coordination and event management.

  2. Orchestration-based Saga: This method involves a central orchestrator that guides the steps of the saga and oversees the flow of transactions. The orchestrator issues commands to individual services, directing them to execute their local transactions. Although this approach provides centralized control, it introduces a single point of failure and potential performance bottlenecks.

Real-World Use Cases

The Saga pattern is applicable in various practical scenarios:

  • E-commerce Order Processing: When you place an order, the process involves multiple services like inventory management, payment processing, and shipping. Utilizing the Saga pattern ensures that each service performs its tasks consistently and correctly, even if failures happen at any stage.
  • Hotel Reservation Systems: Reserving a hotel room requires the coordination of availability, payment, and confirmation. A saga ensures that each of these steps is executed correctly and triggers compensating actions if errors occur.

Conclusion

Maintaining consistency and data integrity in microservices architecture is crucial. The Saga pattern provides a robust framework to address these challenges by segmenting transactions into smaller, manageable parts and including compensating actions. By adopting the Saga pattern, organizations can develop scalable, flexible, and resilient microservices systems that offer a consistent and reliable user experience.

It's important to note that implementing the Saga pattern requires a thoughtful consideration of your specific use cases and system requirements. Although it presents significant advantages, you should evaluate the trade-offs and choose the most suitable implementation approach based on your unique needs.

在微服務架構中的Saga模式

「整體大於部分之和」這種觀點,由柏拉圖闡述,完美地概括出偉大建築的精髓。偉大的建築是經驗(模式、反模式和戰鬥傷疤)、創造力(跳脫框架的思考、原型製作和使用科學方法)和機械同理心(了解機器在較低級別的運作)的混合體。在實踐中,達成最佳建築驚人地簡單,但卻極度艱難。

簡介

在微服務架構的領域中,維護多個服務之間的數據一致性和完整性具有挑戰性。隨著系統變得日益分散和複雜,傳統的事務處理方法經常力不從心。在這裡,Saga模式來我們的幫助。在這篇博文中,我們將深入探討Saga模式,討論其在微服務架構中的重要性,其好處,實施的考慮因素,以及實際應用。

什麼是Saga模式?

Saga模式是一種設計方法,促進了跨多個微服務的長期交易管理。它通過將大型交易分段為一系列較小的本地交易,解決了分散系統中的一致性問題。每一個本地交易代表一個更廣泛的商業流程中的一個步驟,而這些本地交易的序列構成了一個saga。

Saga模式的核心概念是,補償行為可以在失敗或錯誤的情況下,逆轉已完成交易的影響。這使系統能夠保持數據完整性,並最終達到一致的狀態。

在微服務的背景下,幾乎所有的東西都可以被視為一個saga,特別是任何涉及多個微服務的過程。一個saga中的一個步驟通常執行以下任務之一:

  • 與數據庫進行交互
  • 調用另一個微服務
  • 發布一個事件

Saga模式的優勢

  1. 改善數據一致性:通過將交易分解為較小的步驟,並加入補償行為,Saga模式確保即使在遇到失敗時,數據仍然在多個服務間保持一致。

  2. 可擴展性和可用性:由於微服務可以獨立地進行擴展和部署,參與saga的每個服務都可以有效地管理其工作負載。這有助於增強系統的整體可擴展性和可用性。

  3. 靈活性和鬆散耦合:Saga模式鼓勵服務之間進行鬆散耦合,因為每個服務都要負責完成saga的一部分。這使服務的開發、部署和維護可以獨立進行,讓團隊能夠自主運營。

實施Saga模式

要將Saga模式付諸實踐,可以採用各種方法。以下是兩種常見的:

  1. 基於編排的Saga:在這種模型中,saga中的每個服務都直接與其他服務進行通信。他們發布事件或訊息,表示他們的本地交易已完成,其他服務訂閱這些事件並做出相應反應。雖然編排方法消除了對集中式協調者的需求,但需要精心協調和事件管理。

  2. 基於協調的Saga:這種方法包括一個集中式的協調者,該協調者指導著saga的步驟,並監督交易的流動。協調者向單個服務發出命令,指導他們執行他們的本地交易。雖然這種方法提供了集中化的控制,但它引入了一個失敗的單點和潛在性能瓶頸。

實際範例

Saga模式可以應用於各種實際情況:

  • 電子商務訂單處理:當你下訂單時,該過程涉及多個服務,如庫存管理、付款處理和運輸。使用Saga模式確保每個服務都以一致和正確的方式執行其任務,即使在任何階段都有失敗發生。

  • 酒店預定系統:預定酒店房間需要協調可用性、付款和確認。一個saga確保每一步都得以正確執行,並在出現錯誤時觸發補償行為。

總結

在微服務架構中維護一致性和數據完整性至關重要。Saga模式提供了強健的框架,通過將交易切割為較小的、易於管理的部分,並包含補償行為來解決這些挑戰。通過採用Saga模式,組織可以開發出可擴展、靈活、有韌性的微服務系統,提供一致和可靠的用戶體驗。

重要的是要注意,實施Saga模式需要根據你的特定使用案例和系統需求進行深思熟慮。雖然它具有顯著的優點,但你應評估權衡並根據你的獨特需求選擇最合適的實施方法。

Challenges of MBA Programs

I graduated from the part-time Master of Business Administration (MBA) program at the Chinese University of Hong Kong in 2019. An MBA degree has long been considered one of the most prestigious and valuable qualifications in the business world. However, despite its popularity and reputation, many MBA programs also face a number of significant challenges, such as declining attractiveness to prospective students, fluctuating global rankings, and uncertain career prospects for graduates. A frequently asked question among my friends is whether pursuing an MBA is worth it.

One major challenge facing MBA programs is the declining number of applicants. For example, MBA programs in Hong Kong have been significantly impacted by the pandemic and political unrest, leading to a decline in applications for the third consecutive year. This downward trend is a cause for concern among business schools. Several factors may contribute to this decline. One possible reason is the escalating cost of MBA programs, which can deter many international students. Another potential factor is the reduced recognition of these qualifications by employers, especially in Singapore, which lowers the perceived value of the investment.

In my opinion, the worth of an MBA program depends on your personal career goals and the specific program you're considering. An MBA can be a valuable investment, equipping graduates with a wide range of business skills and knowledge, including leadership, strategic thinking, financial analysis, and communication. These skills are highly sought-after by employers and can help you advance your career and increase your earning potential. More importantly, the network and friendships formed through the MBA program have broadened my perspective. Keeping an open mind can also pave the way for new opportunities.

Another challenge is the inconsistency of international rankings. While rankings can be a useful tool for students when choosing an MBA program, they can also be unreliable. Different ranking systems employ different criteria and methodologies, resulting in disparate outcomes. This inconsistency makes it difficult for prospective students to accurately compare and evaluate different MBA programs.

Many people are unaware of the methodology behind Financial Times' business school rankings. The system only considers full-time MBA students and excludes part-time programs. Graduates from years past also influence the ranking through survey responses. If graduates do not respond to the survey or cannot provide updated salary information, this could negatively impact the school's ranking. Also, career changes or relocations by alumni can skew the ranking, which may not necessarily be a fair metric.

Graduates may also face challenges in finding employment and progressing in their careers. Although an MBA can impart valuable skills and knowledge, it doesn't guarantee success in the business world. The degree may open some doors, but graduates often face intense competition for top positions. The current economic climate can further complicate job searches. For instance, there may be layoffs and fewer entry-level opportunities in investment banking. Employers might prefer candidates with different types of experience over MBA graduates.

Personally, I believe the value of an MBA degree may be diminishing. This devaluation could lead to a situation where an MBA is no longer a minimum requirement for certain positions, thus failing to differentiate candidates. This trend is concerning for society at large, as it limits opportunities for individuals with potential and ambition. Ignoring the merits of diverse backgrounds could result in social mobility issues, where opportunities are only available to a lucky few.

Overall, MBA programs face numerous challenges that affect their appeal to prospective students and their potential for career advancement. Despite these challenges, they also present opportunities for business schools to adapt and innovate. By addressing these challenges head-on, MBA programs can continue to offer valuable education and prepare graduates for future career success. As a CUHK MBA graduate, I found the program provided quality education, excellent career prospects, and unique insights into doing business with China—particularly beneficial for international students.

Ultimately, the decision to pursue an MBA should be based on a thorough evaluation of the costs and benefits. You should consider your career goals, personal circumstances, and financial situation before making a decision. Research various MBA programs, taking into account factors like accreditation, reputation, curriculum, and alumni networks. By doing so, you can make an informed decision on whether an MBA program is the right fit for you. If you are interested in learning more about the CUHK MBA program, feel free to drop me a message on LinkedIn. I would be happy to answer your questions.

MBA課程的挑戰

我在2019年從香港中文大學的MBA(工商管理碩士)兼職課程畢業。長期以來,MBA學位一直被認為是商界中最具威望和價值的學歷之一。然而,儘管MBA課程大受歡迎且名聲在外,許多課程也面臨許多重大挑戰,例如吸引潛在學生的吸引力下降、全球排名波動以及畢業生的職業前景不確定。我朋友之間常問的一個問題是攻讀一個MBA課程是否值得。

MBA課程面臨的一個主要挑戰是申請人數下降。例如,香港的MBA課程受到大流行病和政治動盪的重大影響,導致申請數量連續三年下降。這種下行趨勢讓商學院對此感到憂慮。可能貢獻於此下降的幾個因素,一個可能的原因是MBA課程的上升成本,這可能嚇跑許多國際學生。另一個可能的因素是雇主對這些資格的認可度下降,特別是在新加坡,這降低了投資的感知價值。

我認為,一個MBA課程的價值取決於你的個人職業目標和你正在考慮的特定課程。MBA可能是一個有價值的投資,為畢業生裝備一系列的商業技能和知識,包括領導力、策略思考、財務分析和溝通。這些技能深受雇主的歡迎,並能幫助你提升你的職業生涯和提高你的收入潛力。更重要的是,通過MBA課程建立的網絡和友誼擴大了我的視野。保持開放的心態也可以為新機會鋪平道路。

另一個挑戰是國際排名的不一致性。儘管排名可能是學生選擇MBA課程時的有用工具,但它們也可能不可靠。不同的排名系統使用不同的標準和方法,導致不同的結果。這種不一致性使潛在學生難以準確比較和評估不同的MBA課程。

許多人對於《金融時報》商學院排名的背後方法並不了解。該系統只考慮全日制MBA學生,並排除兼職課程。過去幾年的畢業生也透過調查回應影響排名。如果畢業生未回應調查或無法提供最新的工資資訊,這可能對學校的排名產生負面影響。此外,校友的職業變動或重新定位可能會對排名產生影響,這可能並不一定是一個公正的衡量標準。

畢業生可能也在尋找工作和職業發展方面面臨挑戰。雖然MBA可以傳授寶貴的技能和知識,但它並不能保證在商界成功。學位可能會打開一些門,但畢業生往往面臨激烈的競爭,尋求最高職位。當前的經濟環境可能會進一步複雜化求職。例如,投資銀行可能會有裁員和較少的入門級機會。雇主可能更喜歡有不同類型經驗的應該者過於MBA畢業生。

就我個人而言,我認為MBA學位的價值可能正在減少。這種貶值可能導致一種情況,即MBA不再是某些職位的最低要求,從而無法區分候選人。這種趨勢對整個社會來說是令人擔憂的,因為它限制了具有潛力和野心的個人的機會。忽視多元背景的優點可能導致社會流動性問題,即機會只對幸運的少數人開放。

總的來說,MBA課程面臨許多影響其對潛在學生的吸引力和職業發展潛力的挑戰。儘管面臨這些挑戰,但他們也為商學院提供了適應和創新的機會。通過直接面對這些挑戰,MBA課程可以繼續提供有價值的教育,並為畢業生未來的職業成功做好準備。作為一位香港中文大學MBA的畢業生,我發現這個課程提供了高質量的教育,出色的職業前景,以及對與中國做生意的獨特見解-尤其是對國際學生特別有利。

總的來說,決定攻讀MBA應基於對成本和效益的全面評估。在做出決定前,你應該考慮你的職業目標、個人狀況和財務狀況。研究各種MBA課程,考慮認證、聲譽、課程和校友網絡等因素。通過這樣做,你可以做出是否一個MBA課程是否適合你的明智決定。如果你對香港中文大學的MBA課程感興趣,請隨時在LinkedIn上給我留言。我將很樂意回答你的問題。

Checklist for Software Upgrades in Production Environments

Software upgrades are an essential part of maintaining up-to-date and bug-free production environments. However, executing an upgrade can be a complex and challenging task that necessitates careful planning. This blog post offers a software upgrade checklist for production environments to ensure a smooth upgrade process.

Pre-Upgrade Checklist

  • Identify the Scope of the Upgrade: Determine the version you need to upgrade from and to. Review the upgrade path and associated policies. Make note of any exceptions along the upgrade path.

  • Check the Prerequisites: Consult the compatibility matrix for infrastructure versions, such as the database, secret managers, service mesh, Kubernetes cluster, and Docker runtime. It's crucial to consider version compatibility to prevent issues post-deployment.

  • Assess the Impact: Identify any potential risks or issues that may arise during or after the upgrade. Also, estimate any required downtime. Review "What's New," Release Notes, and Important Changes. Schedule downtime for major upgrades like schema changes or database migrations.

  • Develop a Rollback Plan: Creating a rollback plan is essential should the upgrade fail or cause issues. This plan should outline the steps necessary to revert to the previous software version.

  • Notify Stakeholders: Inform end-users, regulators, and internal stakeholders like the IT team and management. Assign a Person in Charge (PIC) for relevant tasks on the checklist and create a Slack channel or Zoom call for real-time communication.

  • Check Configuration: Review any new fields that need to be configured, or assess whether the default values are appropriate for your environment. Update the configuration files to match the new version.

  • Access Secrets: Ensure that all necessary secrets, like the root database password, are available in the secret manager. Update them as needed.

  • Conduct a Dry Run: Perform the upgrade in a non-production environment to identify potential issues or risks.

During Upgrade Checklist

  • Execute the Upgrade: Start the upgrade by following the steps in the official documentation. Closely monitor the process to catch any issues or errors.

  • Health Check: After completing the upgrade, assess the system’s status. If you encounter unexpected issues like pods crash-looping, raise a production issue and contact the relevant team.

Post-Upgrade Checklist

  • Perform Manual Post-Upgrade Steps: Follow any additional instructions as per the documentation. Typical tasks might include garbage collection or removing unused resources.

  • Verify System Functionality: Confirm that the upgraded system functions correctly and that all data and configurations have been properly migrated.

  • Perform a Sanity Check: Conduct user acceptance tests to ensure that the system meets all requirements and that end-users are satisfied.

  • Monitor Metrics: Use dashboards like Grafana to identify any abnormal behavior and review logs for error messages.

  • (For Database Upgrades Only): Check hashing schema columns and procedures such as query result generation, sorting, hashing, and comparison, as well as row counting.

  • Update Documentation: Revise all relevant internal documentation to reflect changes made during the upgrade.

  • Conduct a Post-Implementation Review: Evaluate the success of the upgrade and identify areas for improvement.

Conclusion

Upgrading to a new software version in a production environment is a critical process. A well-structured checklist can make the upgrade go more smoothly. This checklist should be tailored to meet the specific needs of each system and updated regularly to reflect changes in either the production environment or the software version in use.

進行生產環境軟體升級的清單

軟體升級是維護最新且無錯誤生產環境的必要部分。然而,執行升級可能是一項複雜且具挑戰性的任務,需要仔細的規劃。本博客文章提供一個生產環境軟體升級清單,以確保順利的升級過程。

升級前清單

  • 確定升級的範圍: 確定需要從哪個版本升級到哪個版本。審核升級路徑和相關政策。記錄升級路徑上的任何異常。

  • 檢查前提條件: 查詢基礎版本的相容性矩陣,如資料庫、密碼管理器、服務網格、Kubernetes叢集和 Docker 運行時間。考慮版本兼容性以防止部署後出現問題是至關重要的。

  • 評估影響: 確定在升級過程中或之後可能出現的任何潛在風險或問題。同時,估算可能需要的停機時間。回顧「新功能」,發佈說明和重要變化。為大型升級如架構變更或資料庫遷移安排停機時間。

  • 制定回滾計劃: 如果升級失敗或造成問題,創建回滾計劃是必要的。此計劃應描述回滾到先前軟體版本所必需的步驟。

  • 通知相關人員: 通知最終用戶、監管機構和內部持分者(如 IT團隊和管理層)。指派負責人(PIC)處理清單上的相關任務,並建立Slack頻道或Zoom通話來進行即時通訊。

  • 檢查設定: 審查需要設定的任何新欄位,或評估預設值是否適合您的環境。更新設定文件以匹配新版本。

  • 存取密碼: 確保在秘密管理器中可用所有必要的秘密,例如根資料庫密碼。根據需要更新它們。

  • 進行模擬演練: 在非生產環境中進行升級,以確定潛在的問題或風險。

升級中清單

  • 執行升級: 按照官方文件中的步驟開始升級。密切監控這個過程,以便捕捉任何問題或錯誤。

  • 健康檢查: 升級完成後,評估系統的狀態。如果遇到未預期的問題,例如pod無窮迴圈崩潰,提出生產議題並聯絡相關團隊。

升級後清單

  • 執行手動升級後步驟: 根據文件進行任何額外的操作。典型的任務可能包括垃圾回收或刪除未使用的資源。

  • 驗證系統功能: 確認升級後的系統運行正常,且所有數據和配置已正確遷移。

  • 進行檢查: 進行用戶驗收測試,以確保系統達到所有要求,並且最終用戶感到滿意。

  • 監控指標: 使用像Grafana這樣的儀表板來識別任何異常行為,並回顧錯誤消息的日誌。

  • (僅限於資料庫升級): 檢查雜湊模式的列和過程,如查詢結果生成、排序、雜湊和比較,以及行計數。

  • 更新文件: 修訂所有相關的內部文件以反映升級期間所做的變更。

  • 進行升級後審查: 評估升級的成功情況並確定改善範疇。

總結

在生產環境中升級到新軟體版本是一個重要的過程,一個結構良好的清單可以使升級過程更順利。此清單應根據每個系統的特定需求進行定制,並定期更新以反映生產環境或正在使用的軟體版本的變化。

Digital Transformation

Digital transformation is a crucial strategy for any organization seeking to stay competitive in today's market. It involves leveraging digital technologies to create value and enhance customer experiences. There are three key pillars of transformation: digital, data, and talent, all focused on delivering value to customers.

Using data effectively is critical for digital transformation. Some guiding principles for using data include capturing customer transactions daily, investing in promotions to encourage habitual usage, and exploring new revenue models. To improve analytics, organizations can implement a feature store, use better modeling techniques, and draw upon the diverse experiences of their teams, among other strategies.

In the banking sector, digital transformation can lead to personalization, scalability, and efficiency. Various types of digital banks exist in the market, including challenger banks, offshore digital banks, banking-as-a-service players, and digitized hybrid banks.

To stand out, digital banks can leverage hyper-personalization, data-driven engagement, and personalized parameters. Organizations should focus on continuous learning and skill-building, while also being clear about the strategic intent of their journey.

For a successful digital transformation, sponsorship and culture are key factors, along with a willingness to change operating models. Commercial governance should also be embedded into the transformation process.

In conclusion, digital transformation is all about creating value. By leveraging digital platforms, data, and talent, organizations can improve customer experiences, maintain competitiveness, and grow their businesses.

數位轉型

數位轉型對於任何希望在當今市場保持競爭力的組織來說都是一項關鍵策略。它涉及利用數位技術創造價值並提升客戶體驗。數位轉型的三個關鍵支柱是:數位、資料和人才,所有這些都專注於為客戶提供價值。

有效使用資料對於數位轉型至關重要。使用資料的一些指導原則包括每天捕捉客戶交易記錄,投資於促銷活動以鼓勵常規使用,並探索新的收入模式。為了改進分析,組織可以實施特徵儲存庫, 使用更好的建模技術並汲取他們的團隊多元化的經驗,以及其他策略。

在銀行業中,數位轉型可以帶來個性化,可擴展性和效率。市場上存在各種類型的數位銀行,包括挑戰者銀行,離岸數位銀行,銀行即服務玩家和數位化混合銀行。

為了突出,數位銀行可以利用超級個性化,資料驅動的參與,和個性化參數。組織應專注於持續學習和技能提升,同時明確他們旅程的策略意圖。

對於成功的數位轉型,贊助和文化是關鍵因素,還有願意改變營運模式的意願。商業治理也應該被嵌入轉型過程中。

總結,數位轉型就是關於創造價值。通過利用數位平台、資料和人才,組織可以提升客戶體驗,保持競爭力,並擴大他們的業務。

Setting Up Python with Pyenv

Setting up Python on your local machine can be challenging, especially when you need to manage multiple Python versions. Pyenv comes in handy when you need to reproduce an issue in a specific Python environment that you don't currently have. In this blog post, we'll explore how to set up Python using pyenv.

What is Pyenv?

Pyenv is a straightforward tool that allows you to install and manage multiple versions of Python on your local machine. It enables seamless switching between different Python versions and provides a clean, isolated environment for each one, ensuring that your projects remain unaffected by changes in other versions.

Installing Pyenv

Before using pyenv, it's a good idea to remove any existing instances of pip that aren't managed by pyenv. This is a precautionary step that could prevent conflicts down the line.

The installation process varies depending on your operating system. For Linux users, you'll first need to download the required dependencies for pyenv to function properly:

apt install -y make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev \
libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev python-openssl \
git

Next, clone the pyenv repository:

git clone https://github.com/pyenv/pyenv.git ~/.pyenv

This command installs pyenv in the ~/.pyenv directory on your system. To set up your profile:

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc

You'll need to relaunch your terminal for these changes to take effect.

For Mac users, pyenv can be installed using Homebrew:

brew install pyenv

Once pyenv is installed, you can begin using it to manage your Python installations.

Installing Python Versions

To install a specific Python version, use the pyenv install command followed by the version number. For instance, to install Python 3.9.6:

pyenv install 3.9.6

This command downloads and installs Python 3.9.6 in the ~/.pyenv/versions directory.

You can list all installed Python versions with the versions command:

pyenv versions
  system
  * 3.7.10 (set by /Users/user/.pyenv/version)
  * 3.9.6 (set by /Users/user/.pyenv/version)

Setting the Global Python Version

To specify a global Python version for all your projects, use the pyenv global command:

pyenv global 3.9.2

This sets Python 3.9.2 as the default version for all new shell sessions.

Setting the Local Python Version

To set the Python version for a specific project, use the pyenv local command:

pyenv local 3.7.3

This creates a .python-version file in the current directory, indicating which Python version should be used for that project. Note that you will need to install any necessary dependencies for each Python version you switch to.

Conclusion

Pyenv is a powerful tool for managing multiple Python versions on your local machine. It offers clean, isolated environments for each Python version, ensuring your projects remain unaffected by any changes in other versions. With pyenv, switching between Python versions and setting both global and local versions for your projects becomes a straightforward task.

使用 Pyenv 設定 Python

在你的本地機器上設定Python可能是一個挑戰,特別是當你需要管理多個Python版本時。如果你需要在某個專門的Python環境中複製一個問題,而那個環境你目前沒有,那麼Pyenv會非常方便。在這篇博客文章中,我們將探討如何使用pyenv設定Python。

什麼是Pyenv?

Pyenv是一個直接的工具,可以讓你在本地機器上安裝和管理多版本的Python。它可以順暢地切換不同的Python版本並為每一個版本提供一個乾淨的、隔離環境,確保你的項目不受其他版本變化的影響。

安裝Pyenv

在使用pyenv之前,建議移除任何未被pyenv管理的pip實例。這是一個預防性的步驟,可能可以預防未來的衝突。

安裝過程取決於你的操作系統。對於Linux用戶,你首先需要下載pyenv正常運作所需的依賴項:

apt install -y make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev \
libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev python-openssl \
git

接下來,克隆pyenv存儲庫:

git clone https://github.com/pyenv/pyenv.git ~/.pyenv

此命令將在你的系統的~/.pyenv目錄中安裝pyenv。要設置你的配置文件:

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc

你需要重新啟動你的終端機以使這些變更生效。

對於Mac用戶,可以使用Homebrew安裝pyenv:

brew install pyenv

一旦安裝了pyenv,你就可以開始使用它來管理你的Python安裝。

安裝Python版本

要安裝特定的Python版本,使用pyenv install命令後跟版本號。例如,安裝Python 3.9.6:

pyenv install 3.9.6

這個命令將在~/.pyenv/versions目錄中下載和安裝Python 3.9.6。

你可以使用versions命令列出所有已安裝的Python版本:

pyenv versions
  system
  * 3.7.10 (set by /Users/user/.pyenv/version)
  * 3.9.6 (set by /Users/user/.pyenv/version)

設定全域Python版本

要為所有你的項目指定一個全域Python版本,使用pyenv global命令:

pyenv global 3.9.2

這將設定Python 3.9.2為所有新的shell session的默認版本。

設定本地Python版本

要為特定項目設定Python版本,使用pyenv local命令:

pyenv local 3.7.3

這會在當前目錄創建一個.python-version文件,指出該項目應該使用哪個Python版本。請注意,當你切換到每個Python版本時,你需要安裝所有必需的依賴項。

結論

Pyenv是一個強大的工具,能夠在你的本地機器上管理多版本的Python。它為每個Python版本提供乾淨、隔離的環境,確保你的項目不受其他版本變化的影響。有了pyenv,切換Python版本並為你的項目設置全域和本地版本變得直接簡單。