понедельник, 28 декабря 2020 г.

1 of 50. eCommerce Django + React + Android, Install Django.

github
https://github.com/manas-anarov/kungfu_shop_two/tree/1_part


install virtual envoirment
pip3 install pipenv

create  folder
mkdir kungfu_shop_two;
cd
kungfu_shop_two;

install env for project
pipenv install

activate
pipenv shell

install django

pipenv install django~=3.1.4


start django project
django-admin startproject shop_django;

cd shop_django;



start server
python manage.py runserver;

 

open next link

http://127.0.0.1:8000/

суббота, 26 декабря 2020 г.

Django rest first application, Delete Post DestroyAPIView. Part 5

delete post





github
https://github.com/manas-anarov/django_3_ninja/tree/5_part



blog/views.py
from .serializers import (
    ListSerializer,
    AddSerializer,
    ShowSerializer,
    DeleteSerializer,
)

from rest_framework.generics import (
    ListAPIView,    
    CreateAPIView,
    RetrieveAPIView,
    DestroyAPIView,
)

from blog.models import Post

class DeletePost(DestroyAPIView):
    queryset = Post.objects.all()
    serializer_class = DeleteSerializer
    lookup_field = 'id'




blog/serializers.py
class DeleteSerializer(ModelSerializer):
    class Meta:
        model = Post




blog/urls.py
urlpatterns = [
    path('list/', views.PostListAPIView.as_view(), name='blog-list'),
    path('add/', views.AddPost.as_view(), name='blog-add'),
    path('<id>/', views.ShowPost.as_view(), name='blog-show'),
    path('delete/<id>/', views.DeletePost.as_view(), name='blog-delete'),
]




runserver
python manage.py runserver




open link
http://localhost:8000/api/v1/post/list

delete post
http://localhost:8000/api/v1/post/delete/1



How to display json data in listview . Android





platform.json
{
    "platform": [{
            "name": "Windows"
        },
        {
            "name": "Linux"
        },
        {
            "name": "MacOs"
        }
    ]
}



AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />


res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.samuray.myapplication.MainActivity">

    <ListView
        android:id="@+id/lvMain"
        android:layout_width="368dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp" />
</android.support.constraint.ConstraintLayout>



res/layout/item.xml
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#FFF"
    android:gravity="left">
    
    <TextView
        android:layout_height="25dp"
        android:layout_width="wrap_content"
        android:text="+15"
        android:textColor="#000"
        android:textSize="19sp"
        android:id="@+id/name_item"
        android:textStyle="bold"
        android:gravity="center"/>
</LinearLayout>



MainActivity.java
package com.example.samuray.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.os.AsyncTask;

import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new ParseTask().execute();
    }
    private class ParseTask extends AsyncTask<Void, Void, String> {

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        String resultJson = "";

        @Override
        protected String doInBackground(Void... params) {
            try {
                String $url_json = "http://www.anar8.ru/test/1/platform.json";
                URL url = new URL($url_json);

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();

                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }

                resultJson = buffer.toString();
                Log.d("FOR_LOG", resultJson);

            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultJson;
        }


        protected void onPostExecute(String strJson) {
            super.onPostExecute(strJson);

            final ListView lView = (ListView) findViewById(R.id.lvMain);

            String[] from = {"name_item"};
            int[] to = {R.id.name_item};
            ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> hashmap;

            try {
                JSONObject json = new JSONObject(strJson);
                JSONArray jArray = json.getJSONArray("platform");

                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject friend = jArray.getJSONObject(i);

                    String nameOS = friend.getString("name");
                    Log.d("FOR_LOG", nameOS);

                    hashmap = new HashMap<String, String>();
                    hashmap.put("name_item", "" + nameOS);
                    arrayList.add(hashmap);
                }

                final SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, arrayList, R.layout.item, from, to);
                lView.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

пятница, 25 декабря 2020 г.

Django rest first application, Show Post RetrieveAPIView. Part 4



github
https://github.com/manas-anarov/django_3_ninja/tree/4_part



blog/views.py
from .serializers import (
    ListSerializer,
    AddSerializer,
    ShowSerializer,
)


from rest_framework.generics import (
    ListAPIView,
    CreateAPIView,
    RetrieveAPIView,
)

from blog.models import Post

class ShowPost(RetrieveAPIView):
    queryset = Post.objects.all()
    serializer_class = ShowSerializer
    lookup_field = 'id'



blog/serializers.py
class ShowSerializer(ModelSerializer):
    class Meta:
        model = Post
        fields = [
            'id',
            'title',
            'text',
        ]




blog/urls.py
urlpatterns = [
    path('list/', views.PostListAPIView.as_view(), name='blog-list'),
    path('add/', views.AddPost.as_view(), name='blog-add'),
    path('<id>/', views.ShowPost.as_view(), name='blog-show'),
]


open link
http://localhost:8000/api/v1/post/list

show one post
http://localhost:8000/api/v1/post/1

Upload files to django rest framework using react native

Uploading file using api in django rest framework. PythonAnywhere
https://youtu.be/BLN3EPjxQ_E



App.js
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Button,
} from 'react-native';
 
export default class MyApp extends Component {
 
 
  upload_image_to_django (){
 
    PicturePath = "file:///storage/emulated/0/Download/myfoto.jpg";
    URLpath = "http://manas93.pythonanywhere.com/file/upload/";
 
    var formData = new FormData();
    formData.append("file", {uri: PicturePath, name: 'myfoto.jpg', type: 'image/jpg'});
    formData.append("remark", "Hello");
 
    fetch( URLpath, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'multipart/form-data',
      },
      body: formData
     })
    .then((responseJson) => {
      console.log(responseJson);
    })
    .catch(error => {
      console.log(error);
    })
 
  }
 
  render() {
    return (
      <View style={styles.content}>
      <Button       
        title="My Button"
        onPress={this.upload_image_to_django}
      />
      </View>
    );
  }
 
}
 
var styles = StyleSheet.create({
    content:{
        flex:1,
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center'
    }
});

Django rest first application, Create Post CreateAPIView. Part 3




github
https://github.com/manas-anarov/django_3_ninja/tree/3_part



blog/views.py
from .serializers import (
    ListSerializer,
    AddSerializer,
)

from rest_framework.generics import (
    ListAPIView,
    CreateAPIView,
)

from blog.models import Post


class AddPost(CreateAPIView):
    serializer_class = AddSerializer
    queryset = Post.objects.all()




blog/serializers.py
lass AddSerializer(ModelSerializer):
    class Meta:
        model = Post
        fields = [
            'title',
            'text',
        ]



blog/urls.py
urlpatterns = [
    path('list/', views.PostListAPIView.as_view(), name='blog-list'),
    path('add/', views.AddPost.as_view(), name='blog-add'),
]

open link
http://localhost:8000/api/v1/post/list

create post
http://localhost:8000/api/v1/post/add

понедельник, 21 декабря 2020 г.

Django rest first application, Show All Posts ListApiView. Part 2



open project folder
cd django_3_ninja


activate
pipenv shell


open folder
cd ninja_django


create app
python manage.py startapp blog


settings.py
INSTALLED_APPS = [
    'blog',
]



blog/models.py
from django.db import models

class Post(models.Model):
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    title = models.CharField(max_length=200)
    text = models.CharField(max_length=500)

    def __str__(self):
        return self.title



blog/views.py
from .serializers import (
    ListSerializer,
)

from rest_framework.generics import (
    ListAPIView,
)

from blog.models import Post

class PostListAPIView(ListAPIView):
    serializer_class = ListSerializer
    queryset = Post.objects.all()



blog/serializers.py
from rest_framework.serializers import (
    ModelSerializer,
)
from blog.models import Post

class ListSerializer(ModelSerializer):
    class Meta:
        model = Post
        fields = [
            'id',
            'title',
            'text',
        ]



ninja_django/urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/post/', include(('blog.urls', 'blog'), namespace='blog')),
]


blog/urls.py
from blog import views
from django.urls import path

urlpatterns = [
    path('list/', views.PostListAPIView.as_view(), name='blog-list'),
]


install djangorestframework
pipenv install djangorestframework


settings.py
INSTALLED_APPS = [
    'rest_framework',
]


blog/admin.py
from django.contrib import admin
from blog.models import Post

admin.site.register(Post)


create db
python manage.py makemigrations;
python manage.py migrate;


start server
python manage.py runserver;

create admin user
python manage.py createsuperuser

create post
http://localhost:8000/admin

open link
http://localhost:8000/api/v1/post/list

github
https://github.com/manas-anarov/django_3_ninja/tree/2_part

вторник, 15 декабря 2020 г.

Django rest first application, install Django3. Part 1






install virtual envoirment
pip3 install pipenv

create  folder
mkdir django_3_ninja;
cd django_3_ninja
;

install env for project
pipenv install

activate
pipenv shell

install django

pipenv install django~=3.1.4


start django project
django-admin startproject ninja_django;

cd ninja_django;



start server
python manage.py runserver;

 

open next link

http://127.0.0.1:8000/


github

https://github.com/manas-anarov/django_3_ninja/tree/1_part







суббота, 12 декабря 2020 г.

Python Developers (Mid/Senior). Location: Wroclaw

 























We are looking for Python Developers (Mid/Senior).
Ulam Labs (https://ulam.io) is a software house located in Wroclaw and Warsaw. We deliver top software for customers in various industries (blockchain & fintech, telco, production, etc.) mainly in Western Europe and North America.
Currently, we are more than 20 great people strong and specialize in web applications, mostly written in Python and Javascript.
👉 Who: Software House
🌍 Location: Wroclaw
✍️ Employment Type: B2B/UoP
💰 Salary: 7-19k PLN
🤓 Requirements:
➡️ 2+ years of experience in developing web applications using Python 2 or 3
➡️ Experience in at least one modern Javascript framework (Angular, React, or Vue)
➡️ Fluent in English with great communication skills

(c) Barbara Trybulińska(Denisiuk)

Python Team Lead Location: Cyprus, Limassol (Remote/Relocate)

 


На изображении может находиться: океан, небо, пляж, на улице, природа и вода, текст «Python Pytoneaeadjob Team Lead job relocation to Cyprus ©Franco Franco Cappellari» 

Python Team Lead

A product fintech company is looking for Python Team Lead who will lead the Product Development Team and manage the team performance.
Salary: 4000-6000 euro net + bonus
Location: Cyprus, Limassol (Remote/Relocate)
Fulltime/ office
Responsibility:
Full management of the Product Development Team:hiring, onboarding, analyzing, planning, developing, cooperating with a product owner
Qualifications:
⁃5-6 ears of experience in software development (from 2 years Python)
⁃Experience in people management from 1+ years
⁃Experience with Django or others frameworks
⁃Good knowledge of the full-cycle of software development. (Experience in big enterprise companies as a plus).
⁃Fluent written and spoken English and Russian.
We offer:
⁃Relocation package (visa, tickets ant etc.) for a candidate and his/her family
⁃Work permit support
⁃Medical insurance for employees, and family
⁃Different relocation connected costs compensations
Contacts:
@Marina_Pelikh
m.chetverikova@clever-recruiting.com

Django rest first application, PythonAnywhere

 

 

1) pip install --user djangorestframework
2) cd mysite
3) python manage.py startapp restapp
4) python manage.py makemigrations
5) python manage.py migrate
6) python manage.py createsuperuser



mysite/mysite/settings.py
INSTALLED_APPS = [
    'rest_framework',
    'restapp',
]


mysite/restapp/models.py
from django.db import models

class Post(models.Model):
   name = models.CharField(max_length=250)
   text = models.TextField()

   def __str__(self):
      return self.name


mysite/restapp/admin.py
from django.contrib import admin
from restapp.models import Post

admin.site.register(Post)


mysite/restapp/serializers.py
from rest_framework import serializers
from restapp.models import Post

class postSerializer(serializers.ModelSerializer):
   class Meta:
      model = Post
      fields= '__all__'



mysite/restapp/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from restapp.models import Post
from . serializers import postSerializer

class postList(APIView):

   def get(self, request):
      allpost = Post.objects.all()
      serializer = postSerializer(allpost, many=True)
      return Response(serializer.data)

   def post(self):
      pass



mysite/mysite/urls.py
from django.contrib import admin
from django.conf.urls import  url
from restapp import views

urlpatterns = [
    url('admin/', admin.site.urls),
    url('post/', views.postList.as_view()),
]

Android + Django rest first application


 

Django rest first application
[url]http://www.anar8.ru/forum/viewtopic.php?f=29&t=561[/url]
[url]https://youtu.be/_yewu9x0wtQ[/url]


Android

MainActivity.java

package com.example.samuray.myapplication;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new ParseTask().execute();
    }

    private class ParseTask extends AsyncTask<Void, Void, String> {

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        String resultJson = "";

        @Override
        protected String doInBackground(Void... params) {
            try {

                String site_url_json = "http://manas93.pythonanywhere.com/post";
                URL url = new URL(site_url_json);

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();

                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }

                resultJson = buffer.toString();

            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultJson;
        }


        protected void onPostExecute(String strJson) {
            super.onPostExecute(strJson);

            try {
                JSONArray jsonarray = new JSONArray(strJson);
                JSONObject jsonobj = jsonarray.getJSONObject(0);

                String result_json_text =  jsonobj.getString("text");
                Log.d("FOR_LOG", result_json_text);

                TextView textView = (TextView)findViewById(R.id.showtext);
                textView.setText(result_json_text);


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

}


 

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.samuray.myapplication.MainActivity">

    <TextView
        android:id="@+id/showtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>


 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.samuray.myapplication">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Django + Docker. Hello World





install virtual envoirment
pip3 install pipenv

create  folder
mkdir django_docker_hello;
cd django_docker_hello;

install env for project
pipenv install

activate
pipenv shell

install django

pipenv install django~=2.2.17


start django project

django-admin startproject config .


create Docker file
touch Dockerfile


copy next  code
django_docker_hello/Dockerfile

FROM python:3.7-slim
MAINTAINER Django Author
WORKDIR /app
RUN pip install pipenv
COPY . /app
RUN pipenv install --system
EXPOSE 8000
CMD [ "python", "./manage.py", "runserver", "0.0.0.0:8000"] 




build and copy unical id
docker build .
















 

docker run  c42d5b495196 - unical name

docker container run -p 8000:8000 c42d5b495196 


open next link

http://127.0.0.1:8000/


 


 

 

Good Job!!!

source code here

https://github.com/manas-anarov/django_docker_hello





пятница, 11 декабря 2020 г.

Flask + Docker Hello World




git clone flask hello world app
git clone https://github.com/manas-anarov/flask_hello;


change dir

cd flask_hello;


edit app.py
flask_project/app.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == "__main__":
   app.run(host='0.0.0.0')


create Docker file
touch Dockerfile

copy next  code
flask_project/Dockerfile

FROM python:3.7-alpine
MAINTAINER Flask Author
WORKDIR /app
RUN pip install pipenv
COPY . /app
RUN pipenv install --system --deploy
CMD [ "python", "./app.py" ]


build and copy unical id
docker build .


docker run  c42d5b495196 - unical name

docker container run -p 5000:5000 c42d5b495196

 

open next link

http://127.0.0.1:5000/


 

 

 

Good Job!!!

source code here

https://github.com/manas-anarov/flask_hello_docker/

среда, 9 декабря 2020 г.

Flask Hello World pipenv


 

 

install virtual envoirment
pip3 install pipenv

create  folder
mkdir flask_project;
cd flask_project;

install env for project
pipenv install

activate
pipenv shell

install flask
pipenv install flask


create file
touch app.py


copy next  code
flask_project/app.py
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
  app.run(debug=True)



run server
python app.py


open next link

http://127.0.0.1:5000/





Good Job!!!

source code here
https://github.com/manas-anarov/flask_hello