商店项目-5.通过skuId来查询相关的sku,spu,brand,category

相关的类:

通过代码生成器导入4个不同的表,并把下载中的public.key放入

 依赖:

<dependencies>
        <dependency>
            <groupId>com.zb</groupId>
            <artifactId>shop-goods-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.security.oauth.boot</groupId>
                    <artifactId>spring-security-oauth2-autoconfigure</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>
    </dependencies>

Application.yml

server:
  port: 9030
spring:
  application:
    name: shop-goods
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
  datasource:
    url: jdbc:mysql://localhost:3306/shop_goods?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 1002981655
mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    auto-mapping-behavior: FULL  #自动映射的配置 属性和数据库列相同不用配置result
  global-config:      #逻辑删除的配置
    db-config:
      logic-delete-field: deleted
      logic-delete-value: 1
      logic-not-delete-value: 0

ResourceServerConfig代码:

package com.zb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)//激活方法上的PreAuthorize注解
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    //公钥
    private static final String PUBLIC_KEY = "public.key";

    /***
     * 定义JwtTokenStore
     * @param jwtAccessTokenConverter
     * @return
     */
    @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
        return new JwtTokenStore(jwtAccessTokenConverter);
    }

    /***
     * 定义JJwtAccessTokenConverter
     * @return
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setVerifierKey(getPubKey());
        return converter;
    }

    /**
     * 获取非对称加密公钥 Key
     *
     * @return 公钥 Key
     */
    private String getPubKey() {
        Resource resource = new ClassPathResource(PUBLIC_KEY);
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
            BufferedReader br = new BufferedReader(inputStreamReader);
            return br.lines().collect(Collectors.joining("\n"));
        } catch (IOException ioe) {
            return null;
        }
    }

    /***
     * Http安全配置,对每个到达系统的http请求链接进行校验
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //所有请求必须认证通过
        http.authorizeRequests()
                //下边的路径放行
                .antMatchers(
                        "/tb-user-model/info/**"). //配置地址放行
                permitAll()
                .anyRequest().
                authenticated();    //其他地址需要认证授权
    }
}

Swagger2代码:

页面版的postman

package com.zb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * @author zh
 * @ClassName cn.saytime.Swgger2
 * @Description
 * @date 2017-07-10 22:12:31
 */
@Configuration
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zb.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger构建api文档")
                .description("简单优雅的restfun风格,http://blog.csdn.net/saytime")
                .termsOfServiceUrl("http://blog.csdn.net/saytime")
                .version("1.0")
                .build();
    }
}

TokenDecode代码:

package com.zb.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.utils.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class TokenDecode {
    //公钥
    private static final String PUBLIC_KEY = "public.key";

    private static String publickey = "";

    /**
     * 获取非对称加密公钥 Key
     *
     * @return 公钥 Key
     */
    public static String getPubKey() {
        if (!StringUtils.isEmpty(publickey)) {
            return publickey;
        }
        Resource resource = new ClassPathResource(PUBLIC_KEY);
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
            BufferedReader br = new BufferedReader(inputStreamReader);
            publickey = br.lines().collect(Collectors.joining("\n"));
            return publickey;
        } catch (IOException ioe) {
            return null;
        }
    }

    /***
     * 读取令牌数据
     */
    public static Map<String, String> dcodeToken(String token) {
        //校验Jwt
        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(getPubKey()));
        //获取Jwt原始内容
        String claims = jwt.getClaims();
        return JSON.parseObject(claims, Map.class);
    }

    /***
     * 获取用户信息
     * @return
     */
    public static Map<String, String> getUserInfo() {
        //获取授权信息
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        //令牌解码
        return dcodeToken(details.getTokenValue());
    }
}

控制器代码

package com.zb.controller;

import com.zb.dto.BrandDto;
import com.zb.dto.CategoryDto;
import com.zb.dto.SkuDto;
import com.zb.dto.SpuDto;
import com.zb.entity.TbBrandModel;
import com.zb.entity.TbCategoryModel;
import com.zb.entity.TbSkuModel;
import com.zb.entity.TbSpuModel;
import com.zb.service.TbBrandService;
import com.zb.service.TbCategoryService;
import com.zb.service.TbSkuService;
import com.zb.service.TbSpuService;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName TbSkuController
 * @Description 商品表控制器
 * @Author zj
 * @Date 2023/03/27 19:56
 **/
@RestController
@RequestMapping("/tb-sku-model")
@Api(value = "TbSkuController", tags = {"商品表控制器"})
public class TbSkuController {

	@Autowired
	public TbSkuService tbSkuModelService;

	@Autowired
	public TbSpuService tbSpuService;

	@Autowired
	public TbCategoryService tbCategoryService;

	@Autowired
	public TbBrandService tbBrandService;

	@GetMapping("/info")
	public Map<String,Object> info(@RequestParam("skuId") String skuId){
		Map<String,Object> data = new HashMap<>();
		TbSkuModel tbSkuModel = tbSkuModelService.getById(skuId);
		TbSpuModel tbSpuModel = tbSpuService.getById(tbSkuModel.getSpuId());
		TbBrandModel tbBrandModel = tbBrandService.getById(tbSpuModel.getBrandId());
		TbCategoryModel c1 = tbCategoryService.getById(tbSpuModel.getCategory1Id());
		TbCategoryModel c2 = tbCategoryService.getById(tbSpuModel.getCategory2Id());
		TbCategoryModel c3 = tbCategoryService.getById(tbSpuModel.getCategory3Id());

		SkuDto skuDto = new SkuDto();
		SpuDto spuDto = new SpuDto();
		BrandDto brandDto = new BrandDto();
		CategoryDto cd1 = new CategoryDto();
		CategoryDto cd2 = new CategoryDto();
		CategoryDto cd3 = new CategoryDto();

		BeanUtils.copyProperties(tbSkuModel,skuDto);
		BeanUtils.copyProperties(tbSpuModel,spuDto);
		BeanUtils.copyProperties(tbBrandModel,brandDto);
		BeanUtils.copyProperties(c1,cd1);
		BeanUtils.copyProperties(c2,cd2);
		BeanUtils.copyProperties(c3,cd3);

		data.put("sku",skuDto);
		data.put("spu",spuDto);
		data.put("brand",brandDto);
		data.put("c1",cd1);
		data.put("c2",cd2);
		data.put("c3",cd3);
		return data;
	}
}

启动器代码:

package com.zb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableSwagger2
public class GoodsApplication {
    public static void main(String[] args) {
        SpringApplication.run(GoodsApplication.class, args);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,您可以使用 Python 中的 requests 库和 BeautifulSoup 库来实现爬取天猫贝汉美旗舰店最近1个月新品的数据。 首先,您需要使用 requests 库向该店铺页面发送 HTTP 请求,获取 HTML 代码。然后,您可以使用 BeautifulSoup 库解析 HTML 代码,从而获取所需的字段信息。 以下是示例代码: ```python import requests from bs4 import BeautifulSoup # 设置请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # 获取页面 HTML url = 'https://beihanmei.tmall.com/search.htm?spm=a1z10.3-b-s.w4011-14448522565.64.5fb979f0Z6DHiW&search=y&orderType=newOn_desc&tsearch=y' response = requests.get(url, headers=headers) html = response.text # 解析 HTML soup = BeautifulSoup(html, 'html.parser') # 获取商品列表 item_list = soup.find_all('div', {'class': 'product'}) # 遍历商品列表,获取所需的字段信息 for item in item_list: # 获取图片地址 img = item.find('img')['src'] # 获取标题 title = item.find('p', {'class': 'productTitle'}).text.strip() # 获取一口价 price = item.find('p', {'class': 'productPrice'}).text.strip() # 获取 sku 信息 sku_list = item.find_all('li', {'class': 'item'}) for sku in sku_list: # 获取 sku 图片地址 sku_img = sku.find('img')['src'] # 获取 sku 名称 sku_name = sku.find('span', {'class': 'title'}).text.strip() # 获取 sku 价格 sku_price = sku.find('span', {'class': 'price'}).text.strip() # 输出结果 print(img, title, price, sku_img, sku_name, sku_price) ``` 注意:爬取网站数据需要遵守相关法律法规,不能用于商业用途。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小柯Stuart

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值